Simple O(1) space , and O(n) time. EasytoUnderstand sol---by bruteforcemaster

just go with the flow and keep remember what the bruteforcemaster says---- first approach the iterative method and use your bruteforce skills, then start trying to optimize your code.


public class Solution {
    public int isValid(String S) {
        Stack<Character> A = new Stack<Character>();
        int n = S.length();
        int i = 0;
        while(i<n){
//you can use Switch CASE also
                if(A.isEmpty()) A.push(S.charAt(i));
                else if(A.peek()==’(’ && S.charAt(i)==’)’) A.pop();
                else if(A.peek() == ‘[’ && S.charAt(i) == ‘]’) A.pop();
                else if(A.peek() == ‘{’ && S.charAt(i) == ‘}’) A.pop();
                else if(A.peek()==’(’ && (S.charAt(i)==’]’ || S.charAt(i) == ‘}’)) return 0;
                else if(A.peek()==’{’ && (S.charAt(i)==’]’ || S.charAt(i) == ‘)’)) return 0;
                else if(A.peek()==’[’ && (S.charAt(i)==’)’ || S.charAt(i) == ‘}’)) return 0;
                else A.push(S.charAt(i));
            i++;
        }
        if(A.isEmpty())
            return 1;
        else
            return 0;
    }
}

Click here to start solving coding interview questions