【每日一题-leetcode】 20.有效的括号

20.有效的括号

难度简单1475

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true
//使用栈   
public boolean isValid(String s) {
        if(s.length() == 0){
            return true;
        }
        Stack<Character> stack = new Stack();
        for(char c : s.toCharArray()){
            //如果是 [ { ( push到Stack中
            if(c == '{' || c == '[' || c == '('){
                stack.push(c);
            }else{
                if(stack.isEmpty()){
                    return false;
                }
                //将Stack中 [  { ( pop出来 和 c中的遍历 如果相等就消去一对
                Character ch = stack.pop();
                boolean a = (c == '}' && ch != '{');
                boolean b = (c == ']' && ch != '[');
                boolean d = (c == ')' && ch != '(');
                if(a || b || d){
                    return false;
                }
            }
        }
        //最后如果栈中为null 说明 符号正确
        return stack.isEmpty();
    }

时间复杂度:O(n)

public boolean isValid(String s) {
        int length;
        do{
            length = s.length();
            s = s.replace("()","").replace("[]","").replace("{}","");
        }while(length != s.length());
        return s.isBlank();
    }

时间复杂度:O(n^2/2) 建议采用第一种Stack的方式。

原文地址:https://www.cnblogs.com/qxlxi/p/12860666.html