• 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;
        }
    }
    
  • 相关阅读:
    初识 Umbraco CQ
    程序员的利器SourceInsight CQ
    关于Hg的文件过滤 CQ
    蓝桥杯 基本内容
    leedswriting符号
    tiny mission 2021 11 15
    拓扑排序+二分答案+建图
    mission 11.24
    高数积分求面积
    高数积分求弧长
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13500514.html
Copyright © 2020-2023  润新知