class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        char[] chs = s.toCharArray();
        int len = chs.length;
        if((len&1)==1)return false;
        for(int i=0;i<len;i++){
            if(stack.isEmpty()||!isMatch(stack.peek(),chs[i]))
                stack.push(chs[i]);
            else  
                stack.pop();
        }
        return stack.isEmpty();
    }
    public boolean isMatch(char a,char b){
       switch(a){
            case '(': if(b == ')') return true; else return false;
            case '{': if(b == '}') return true; else return false;
            case '[': if(b == ']') return true; else return false;
            default : return false;
        }
    }
}

 

20. 有效的括号

相关文章:

  • 2021-07-03
  • 2022-01-06
  • 2021-11-22
  • 2021-07-03
猜你喜欢
  • 2021-04-30
  • 2021-11-17
  • 2021-04-16
  • 2021-06-06
相关资源
相似解决方案