zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    HDOJ 450题留念
    有关VIM的一些笔记
    hdu 2715
    POJ 1004
    链表的创建,添加结点,打印...
    C++ 静态数据成员小谈
    自定义String类
    sizeof/strlen小论
    多态之重载多态运算符重载那些事
    01背包问题
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13500514.html
Copyright © 2011-2022 走看看