Java Solution using Stack - O(n) time complexity


  • 0
    P
    class Solution {
        public boolean isValid(String s) {
            Stack<Character> stack = new Stack<Character>();
            for(int i = 0; i < s.length(); i++){
                if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{'){
                    stack.push(s.charAt(i));
                } else if(!stack.empty()){
                    char removal = stack.pop();
                    if((removal == '(' && s.charAt(i) != ')' )|| (removal == '{' && s.charAt(i) != '}' ) 
                     || (removal == '[' && s.charAt(i) != ']' )){
                        return false;
                    }
                } else {
                    return false;
                }
            }
            return stack.empty();
        }
    }
    

Log in to reply
 

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