Java Solution using Stacks


  • 0
    E
    public class Solution {
        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(s.charAt(i)==')'){
                    if(stack.isEmpty()){
                        return false;
                    }
                    else if(stack.peek()=='('){
                       stack.pop(); 
                    }
                    else{
                        return false;
                    }
                }
                else if(s.charAt(i)=='}'){
                    if(stack.isEmpty()){
                        return false;
                    }
                    else if(stack.peek()=='{'){
                       stack.pop(); 
                    }
                    else{
                        return false;
                    }
                }
                else if(s.charAt(i)==']'){
                    if(stack.isEmpty()){
                        return false;
                    }
                    else if(stack.peek()=='['){
                       stack.pop(); 
                    }
                    else{
                        return false;
                    }
                }
            }
            if(stack.isEmpty()){
                return true;
            }
            return false;
        }
    }
    

Log in to reply
 

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