balance bracket solution in c 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 balance java
class Parser{
static HashMap<Character,Character> bracket_map = new HashMap<>();
static {
bracket_map.put(')', '(');
bracket_map.put('}','{');
bracket_map.put(']','[');
}
boolean isBalanced(String s){
Stack<Character> stack = new Stack<>();
char temp;
for (int i = 0; i < s.length(); i++) {
temp = s.charAt(i);
if(temp == '{' || temp == '[' || temp == '('){
stack.push(temp);
}else {
if(stack.isEmpty() || stack.peek() != bracket_map.get(temp)) return false;
stack.pop();
}
}
return stack.isEmpty();
}
}