zoukankan      html  css  js  c++  java
  • LC 20 Valid Parentheses

    问题

    Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

    An input string is valid if:

    1. Open brackets must be closed by the same type of brackets.
    2. Open brackets must be closed in the correct order.

    Note that an empty string is also considered valid.

    Example 1:

    Input: "()"
    Output: true
    

    Example 2:

    Input: "()[]{}"
    Output: true
    

    Example 3:

    Input: "(]"
    Output: false

    参考答案

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for (char c : s.toCharArray()) {
            if (c == '(')
                stack.push(')');
            else if (c == '{')
                stack.push('}');
            else if (c == '[')
                stack.push(']');
            else if (stack.isEmpty() || stack.pop() != c)
                return false;
        }
        return stack.isEmpty();
    }

    额外注释

    这个代码很厉害。

    首先建立一个 character 的 stack,作用是按照次序存储右半边的信息。等所有左半边的检查完毕,所有对应信息被push进stack,那么就可以开始检查右半边。

    核心在于最后一个else if, 条件是『stack是否为空 or stack.pop 的值不等于检测值』,一旦其中一个成立,都返回false。

    • stack是空 -> 没有东西进入stack -> c不满足任何括号条件。
    • for循环 检查到右半边:最后被push被stack的信息 不等于 右半边开始的信息 -> 不对称 -> 返回 false

    巧妙的是,判断完以后,stack最末尾的信息将会被pop出去,而最后结束了循环,如果stack全部被pop出去,那么stack为空,意味着,所有被推进stack的信息都被检查完毕,没有机会进入最后的 else if 条件。

    大功告成。

  • 相关阅读:
    数组与字符串的相互转换
    数组新增,修改json数据
    百度Ueditor设置图片自动压缩
    微信小程序——自定义图标组件
    微信小程序——自定义导航栏
    微信小程序——网盘图片预览
    微信小程序——星星评分
    微信小程序——页面中调用组件方法
    Vue路由获取路由参数
    C#随机颜色和随机字母
  • 原文地址:https://www.cnblogs.com/kykai/p/11538232.html
Copyright © 2011-2022 走看看