My concise Java solution


  • 0
    C
    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() && ((s.charAt(i) == ')' && stack.peek() == '(') || (s.charAt(i)== ']' && stack.peek() == '[') || (s.charAt(i) == '}'&& stack.peek() == '{')))
                    stack.pop();
                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.