Use ASCII and dummy value and stack to get simple code


  • 0
    Z

    The ASCII code of (){}[] are: 40 41 123 125 91 93, so the code just to compare the ascii value.

    Add a dummy value to stack first, to simplify the code using stack.peek().

        public boolean isValid(String s) {
            Stack<Integer> stack = new Stack<Integer>();
            stack.push(0);
            for (int i = 0; i < s.length(); i++) {
                int c = s.charAt(i);
                if (stack.peek() + 1 == c || stack.peek() + 2 == c)
                    stack.pop();
                else
                    stack.push(c);
            }
            return stack.size() == 1;
        }

Log in to reply
 

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