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 条件。

    大功告成。

  • 相关阅读:
    【设计模式】3、工厂方法模式
    【设计模式】2、生成器模式(建造者模式)
    【设计模式】1、抽象工厂模式
    UNION 和UNION ALL
    树的遍历
    相关前台跨域的解决方式
    有关this指针指向问题
    有关箭头函数
    深入理解js的变量提升和函数提升
    linux tail 命令详解
  • 原文地址:https://www.cnblogs.com/kykai/p/11538232.html
Copyright © 2011-2022 走看看