zoukankan      html  css  js  c++  java
  • 【每日一题-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的方式。

  • 相关阅读:
    <c:forEach>详解
    JSP基本_JSTL
    鼠标显示效果的形状设置
    linux7.3+nginx1.1+tomcat8.5 搭建负载均衡
    安装zabbix
    Centos7 systemctl使用
    Centos7 yum安装 Lnmp以及Lamp
    Centos7 LAMP环境下安装zabbix3.0
    centos 7.0 搭建LAMP环境
    mysql 配置参数详解
  • 原文地址:https://www.cnblogs.com/qxlxi/p/12860666.html
Copyright © 2011-2022 走看看