Easy Java solution with stack


  • 0
    C
    public boolean isValid(String s) {
        int n = s.length();
        Stack<Character> stack = new Stack<Character>();
        for(int i = 0; i < n ; i++){
            char c = s.charAt(i);
            if(c == '{' || c == '(' || c == '['){
                stack.add(c);
            }else{
                if(stack.isEmpty()){ // if no '{, ( , [' in the stack 
                    return false;
                }
                char pre = stack.pop();
                if(c == '}'){
                    if(pre != '{'){
                        return false;
                    }
                }else if ( c == ']'){
                    if(pre != '['){
                        return false;
                    }
                }else {
                    if(pre != '('){
                        return false;
                    }
                }
            }
        }
        return stack.isEmpty();
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.