[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.

     这道题不算太难。因为已经说了包含的characters只有这六种。因此可以用很简单的if statement,除了这六个以外的都return false。

     另外根据stack,后进先出的特点,我们可以借助stack来计算。

     代码如下。~

public class Solution {
    public boolean isValid(String s) {
        if(s.length()<=1){
            return false;
        }
        Stack<Character> stack=new Stack<Character>();
        char[] curr=s.toCharArray();
        
        for(int i=0;i<s.length();i++){
            if(curr[i]=='('||curr[i]=='{'||curr[i]=='['){
                stack.push(curr[i]);
            }else if(curr[i]==')'||curr[i]==']'||curr[i]=='}'){
                try{
                    char compare=stack.peek();
                    if((curr[i]==')'&&compare=='(')||(curr[i]==']'&&compare=='[')||(curr[i]=='}'&&compare=='{')){
                        stack.pop();
                    }else{
                    return false;
                    }
                }
                catch (Exception e){
                    return false;
                }
            }else{
                return false;
            }
        }
        if(stack.size()!=0){
            return false;
        }
        return true;
    }
}

 

     

 

     

posted @ 2015-08-24 15:06  李小橘er  阅读(188)  评论(0)    收藏  举报