Solution in Java


  • 0
    R
        public boolean isValid(String s) {
            char chArr[]=s.toCharArray();
            Stack<Character> stack=new Stack();
            for(Character ch:chArr){
                if(ch=='(' || ch=='{' || ch=='['){
                    stack.push(ch);
                }else if(ch==')'){
                    if(stack.isEmpty() || stack.peek() != '(')
                        return false;
                    stack.pop();
                }else if(ch=='}'){
                    if(stack.isEmpty() || stack.peek() != '{')
                        return false;
                    stack.pop();
                }else if(ch==']'){
                    if(stack.isEmpty() || stack.peek() != '[')
                        return false;
                    stack.pop();
                }
            }
            return stack.isEmpty();
        }
    

Log in to reply
 

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