问题

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

大功告成。

LC 20 Valid Parentheses的更多相关文章

  1. [Leetcode][Python]20: Valid Parentheses

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 20: Valid Parentheseshttps://oj.leetcod ...

  2. 20. Valid Parentheses【leetcode】

    20. Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', ...

  3. leetcode 20. Valid Parentheses 、32. Longest Valid Parentheses 、

    20. Valid Parentheses 错误解法: "[])"就会报错,没考虑到出现')'.']'.'}'时,stack为空的情况,这种情况也无法匹配 class Soluti ...

  4. 《LeetBook》leetcode题解(20):Valid Parentheses[E]——栈解决括号匹配问题

    我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...

  5. LeetCode解题笔记 - 20. Valid Parentheses

    这星期听别人说在做LeetCode,让他分享一题来看看.试了感觉挺有意思,可以培养自己的思路,还能方便的查看优秀的解决方案.准备自己也开始. 解决方案通常有多种多样,我觉得把自己的解决思路记录下来,阶 ...

  6. leetCode练题——20. Valid Parentheses

    1.题目 20. Valid Parentheses——Easy  Given a string containing just the characters '(', ')', '{', '}',  ...

  7. 刷题20. Valid Parentheses

    一.题目说明 这个题目是20. Valid Parentheses,简单来说就是括号匹配.在学数据结构的时候,用栈可以解决.题目难度是Medium. 二.我的解答 栈涉及的内容不多,push.pop. ...

  8. C# 写 LeetCode easy #20 Valid Parentheses

    20.Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', ...

  9. [LeetCode] 20. Valid Parentheses 验证括号

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

随机推荐

  1. 用docker 下载NGINX nginx安装错误:No package nginx available

    docker 内安装 nginx,提示 解决方案: 1,备份 mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.rep ...

  2. JAVA基础知识|类设计技巧

    1.一定要保证数据私有 2.一定要对数据初始化 3.不要再类中使用过多的基本类型 4.不是所有的域都需要独立的域访问器和域更改器 5.将职责过多的类进行分解 6.类名和方法名要能够体现它们的职责 7. ...

  3. 网络1911、1912 C语言第0次作业批改总结

    网络1911.1912 C语言第0次作业批改总结 题目:C博客作业00--我的第一篇博客 一.评分规则 总分10分,每个问题都务必回答,分值都在问题后面 抄袭 - 0分 博客作业格式不规范,没有用Ma ...

  4. Mac下持续集成-jenkins设置密码及启动

    什么情况呢,现在想起来重新启动jenkins时发现,一切都要从头开始... 输入原始密码: 提示密码在:/var/root/.jenkins/secrets/initialAdminPassword ...

  5. 国内it论坛

    社区是聚集一类具有相同爱好或者相同行业的群体,IT技术社区就是聚集了IT行业内的技术人,在技术社区可以了解到行业的最新进展,学习最前沿的技术,认识有相同爱好的朋友,在一起学习和交流. 技术社区一般有三 ...

  6. Swift 循环

    循环类型 Swift 语言提供了以下几种循环类型.点击链接查看每个类型的详细描述: 循环类型 描述 for-in 遍历一个集合里面的所有元素,例如由数字表示的区间.数组中的元素.字符串中的字符. fo ...

  7. 启动elasticsearch的时候报出Exception in thread "main" SettingsException[Failed to load settings from /usr/local/elasticsearch/config/elasticsearch.yml]; nested: MarkedYAMLException[while scanning a simple ke

    故障现象: [elasticsearch@tiantianml- ~]$ /usr/local/elasticsearch/bin/elasticsearch Exception in thread ...

  8. C++ STL 排序

    #include <iostream>#include <algorithm>#include <deque>#include <vector>#inc ...

  9. 浏览器与NodeJS环境 eventloop异同详解(转)

    结论:浏览器中是一个宏任务,所有微任务,一个宏任务,所有微任务...           NodeJS中,一种宏任务队列所有任务,所有微任务,一种宏任务队列所有任务,所有微任务... ┌─────── ...

  10. [Scikit-learn] *2.3 Clustering - MeanShift

    sklearn.cluster.MeanShift Ref: http://scikit-learn.org/stable/auto_examples/cluster/plot_mean_shift. ...