LeetCode 20 有效的括号

LeetCode 20 有效的括号

给定一个代表包含一系列括号{}、[]、()的字符串,判断该字符串是否是一个合法的字符串(同类型左右括号匹配,且必须是连续的)
辅助栈

class Solution {
    public boolean isValid(String s) {
        if(s==null || s.length()==0) return true;
        
        /*存在先后顺序的情况使用栈来判断*/
        List<Character> stack = new ArrayList<>();
        int top = -1;
        for(int i=0;i<s.length();i++){
            char ch = s.charAt(i);
            switch(ch) {
                case '(':
                case '{':
                case '[': {
                    stack.add(ch);top++;
                    break;
                }
                case ')': {
                    if(top>-1 && stack.get(top)=='('){
                        stack.remove(top);top--;
                        break;
                    }
                    return false;
                }
                case '}': {
                    if(top>-1 && stack.get(top)=='{'){
                        stack.remove(top);top--;
                        break;
                    }
                    return false;
                }
                case ']': {
                    if(top>-1 && stack.get(top)=='['){
                        stack.remove(top);top--;
                        break;
                    }
                    return false;
                }
            }
        }
        if(top!=-1) return false;
        else return true;
    }
}
原文地址:https://www.cnblogs.com/CodeSPA/p/13500514.html