5 line Java solution using stacks (6 ms)


  • 2

    Since the string can only contain brackets, I don't need to do a lot of unnecessary checks
    Also the difference between any open and closed brackets char value should never be greater than 2.

    public boolean isValid(String s) {
            Stack<Character> stack = new Stack<Character>();
            for(char c : s.toCharArray()){
                if (c=='('||c=='{'||c== '[') stack.push(c);
                else if (stack.empty()||Math.abs(c-stack.pop())>2) 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.