Very Slow Java solution


  • 0
    S
    public class Solution {
        public boolean isValid(String s) {
            Stack stack = new Stack();
            int len = s.length();
            
            for(int i=0;i<len;i++) {
                if(stack.isEmpty()) {
                    stack.push(s.charAt(i));
                } else if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{'){
                    stack.push(s.charAt(i));
                } else {
                    char c = (char)stack.pop();
                    
                    switch(c) {
                        case '(':
                            if(s.charAt(i) == ')')
                                continue;
                            else
                                return false;
                        case '[':
                            if(s.charAt(i) == ']')
                                continue;
                            else
                                return false;
                        case '{':
                            if(s.charAt(i) == '}')
                                continue;
                            else
                                return false;
                    }
                }
            }
            
            if(!stack.isEmpty())
                return false;
            return true;
        }
    }

Log in to reply
 

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