Easy to understand Java solution, O(n)


  • 0
    public class Solution {
        private static final String LEFT = "([{";
        private static final String RIGHT = ")]}";
        public boolean isValid(String s) {
            Stack<Character> stack = new Stack<Character>();
            for(char ch : s.toCharArray()){
                if (LEFT.indexOf(ch) != -1) {
                    stack.push(ch);
                } else if(RIGHT.indexOf(ch) != -1){
                    if(stack.empty()) {
                        return false;
                    } else if(ch == ')' && stack.peek().equals('(')
                            || ch == ']' && stack.peek().equals('[')
                            || ch == '}' && stack.peek().equals('{')){
                        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.