My java solution using ASCII code


  • 0
    L
    public class Solution {
        public boolean isValid(String s) {
            if (s == null) return true;
            Stack<Character> stack = new Stack<Character> ();
            stack.push(s.charAt(0));
            int index = 1;
            while (index < s.length()){
                char next = s.charAt(index);
                if (!stack.empty()){
                    char curr = stack.peek();
                    // () are 40,41, [] are 91, 93, {} are 123, 125.
                    if (next-curr != 1 && next-curr != 2){
                        stack.push(next);
                    }else{
                        stack.pop();
                    }
                }else{
                    stack.push(s.charAt(index));                
                }
                index++;
            }
            return stack.empty();
        }
    }

Log in to reply
 

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