JAVA stack solution


  • 0
    Y
    public class Solution {
        public boolean isValid(String s) {
            if(s.length()<2||s.length()%2==1) return false;
            Stack<Character> stack=new Stack<>();
            for(char c:s.toCharArray()){
                if(c=='('||c=='{'||c=='[')
                    stack.push(c);
                if(c==')'||c=='}'||c==']'){
                    if(!stack.empty()){
                        if(stack.peek()=='('&&c!=')') return false;
                        if(stack.peek()=='['&&c!=']') return false;
                        if(stack.peek()=='{'&&c!='}') return false;
                        else stack.pop();
                    }
                }
            }
            return stack.empty()?true:false;
        }
    }
    

Log in to reply
 

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