Write an algorithm to check for balanced parentheses in an expression using stack code example
Example 1: bracket balancing c++
bool correct_paranthesis(string str){
stack<char> stk;
map<char,char> bracket_map;
bracket_map[')'] = '(';
bracket_map['}'] = '{';
bracket_map[']'] = '[';
for(int i=0; i<str.size(); i++){
if(str[i] == '(' || str[i] == '{' || str[i] == '[')
stk.push(str[i]);
if(str[i] == ')' || str[i] == '}' || str[i] == ']'){
if(stk.empty())
return false;
if(stk.top() == bracket_map[str[i]] )
stk.pop();
}
}
return (stk.empty() == true);
}
Example 2: bracket balancing program in java
import java.util.Scanner;
import java.util.ArrayList;
public class BalanceBracket {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter a string with '(', '{' or '['");
String s = sc.nextLine();
String y = isBalanced(s);
System.out.println(y);
}
static String isBalanced(String s)
{
String result = "NO";
ArrayList<String> al = new ArrayList<String>();
for(int i = 0; i < s.length(); i++)
{
if(s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[')
{
al.add(Character.toString(s.charAt(i)));
}
else if(s.charAt(i) == ')' || s.charAt(i) == '}' || s.charAt(i) == ']')
{
if(al.size() != 0 && al.get(al.size()-1).equals("(") && s.charAt(i) == ')')
{
al.remove(al.size()-1);
}
else if(al.size() != 0 && al.get(al.size()-1).equals("{") && s.charAt(i) == '}')
{
al.remove(al.size()-1);
}
else if(al.size() != 0 && al.get(al.size()-1).equals("[") && s.charAt(i) == ']')
{
al.remove(al.size()-1);
}
else
{
return result = "NO";
}
}
}
if(al.isEmpty() == true)
{
return result = "YES";
}
return result;
}
}
Example 3: Algorithm check balanced parentheses
if (null == str || ((str.length() % 2) != 0)) {
return false;
} else {
char[] ch = str.toCharArray();
for (char c : ch) {
if (!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')')) {
return false;
}
}
}