leetcode-20. Valid Parentheses

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

判断字符括号是否匹配正确。

java代码:

public class Solution {
    public boolean isValid(String s) {
        Stack a=new Stack();
        int i=0;
        while(i!=s.length()){
            switch(s.charAt(i)){
                case '[':
                    a.push('[');
                    break;
                case '(':
                    a.push('(');
                    break;
                case '{':
                    a.push('{');
                    break;
                case ')':
                    if(a.empty()||(char)a.pop()!='(')
                    return false;
                    break;
                case '}':
                    if(a.empty()||(char)a.pop()!='{')
                    return false;
                    break;
                case ']':
                    if(a.empty()||(char)a.pop()!='[')
                    return false;
                    break;
            }
                
            
            i++;
        }
        if(!a.empty()){
            return false;
        }
        return true;
    }
}

  

 

posted @ 2017-03-19 13:56  世人谓我恋长安  阅读(142)  评论(0编辑  收藏  举报