Leetcode: Valid Parentheses

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

public boolean isValid(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(s==null||s.length()%2!=0){
            return false;
        }
        ArrayList<Character> leftBrackets = new ArrayList<Character>();
        for(int i=0;i<s.length();i++){
            char curr = s.charAt(i);
            if(curr=='(' || curr=='{' || curr=='[' ){
                leftBrackets.add(curr);
            }else{
                if(leftBrackets.size()==0){
                    return false;
                }
                char lastLeft = leftBrackets.get(leftBrackets.size()-1);
                if((lastLeft=='('&&curr==')') ||
                   (lastLeft=='{'&&curr=='}') ||
                   (lastLeft=='['&&curr==']')){
                       leftBrackets.remove(leftBrackets.size()-1);
                   }else{
                       return false;
                   }
            }
        }
        if(leftBrackets.size()!=0){
            return false;
        }
        return true;        
    }

 

FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *