Algorithm:- The basic idea is to push the right parentheses ), }, ] into the stack each time when we encounter left ones. And if a right bracket appears in the string, we need check if the stack is empty and also whether the top element is the same with that right bracket. If not, the string is not a valid one. At last, we also need check if the stack is empty.
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 | bool isValid(string s) { stack<char> st; //taking stack for keep tracking the order of the brackets.. for(auto i:s) //iterate over each and every elements { if(i=='(' or i=='{' or i=='[') st.push(i); //if current element of the string will be opening bracket then we will just simply push it into the stack else //if control comes to else part, it means that current element is a closing bracket, so check two conditions current element matches with top of the stack and the stack must not be empty... { if(st.empty() or (st.top()=='(' and i!=')') or (st.top()=='{' and i!='}') or (st.top()=='[' and i!=']')) return false; st.pop(); //if control reaches to that line, it means we have got the right pair of brackets, so just pop it. } } return st.empty(); //at last, it may possible that we left something into the stack unpair so return checking stack is empty or not.. } |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for (char c : s.toCharArray()) { if (c == '(') stack.push(')'); else if (c == '{') stack.push('}'); else if (c == '[') stack.push(']'); else if (stack.isEmpty() || stack.pop() != c) return false; } return stack.isEmpty(); } |
Java (without Stack)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public class BalancedParanthesis { public static void main(String[] args) { String exp = "{()}[{}]"; System.out.println(checkBalancedParanthesis(exp)); } private static String checkBalancedParanthesis(String exp) { if(exp.length()==0) return "Empty string"; else if(exp.length()==1) return "Unbalanced"; else { String temp = exp.charAt(0)+""; int i = 1; while(i<=exp.length()-1) { char c = exp.charAt(i); if(c=='(' || c=='{' || c=='[') { temp += c; } else{ char pc = temp.charAt(temp.length()-1); if((pc=='('&&c==')') || (pc=='{' && c=='}') || (pc=='[' && c==']')) temp = temp.substring(0,temp.length()-1); else return "Unbalanced"; } i++; } if(temp.length()==0) return "Balanced"; else return "Unbalanced"; } } } |
Python
1 2 3 4 5 6 7 8 9 10 11 12 | def isValid(s): stack = [] dict = {"]":"[", "}":"{", ")":"("} for char in s: if char in dict.values(): stack.append(char) elif char in dict.keys(): if stack == [] or dict[char] != stack.pop(): return False else: return False return stack == [] |