Easy to understand Java solution using Stack.


  • 0
    Z
      public boolean isValid(String s) {
        if(s.length() == 0 || s == null) return false;
        Stack<Character> stack = new Stack<>();
        for(int i = 0; i < s.length(); i++) {
            Character c = s.charAt(i);
            if(c == '[' || c == '(' || c == '{') {
                stack.push(c);
            } else if(!stack.isEmpty()) {
                Character b = stack.pop();
                if((b == '(' && c != ')') || (b == '[' && c != ']') || (b == '{' && c != '}') )
                    return false;
            } else 
                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.