20. Valid Parentheses[E]有效的括号
题目
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
Example 4:
Input:"([)]"
Output:false
Example 5:
Input:"{[]}"
Output:true
思路
leetcode上的解答是这样的:
先考虑简单的情况:只有一种括号

图1:只有一种括号
定义一个计数器left,如果我们遇到一个开括号,则计数器left加1;如果遇到一个闭括号,此时有两种情况,一是当前left=0,这说明没有配对的开括号,表达式无效;二是left>0,说明还有没配对的开括号,left--。
但是实际情况不止一种括号,但是我们发现,为了保证表达式的每一个子表达式都是也是有效的,每一个闭括号总是与左起最近的开括号是匹配的,如图2。

图2:多个括号的情况
这个时候就要用到栈。在表示问题的递归结构时,由于我们不清楚整体的结构,无法从里到外的解决问题,此时栈可以帮助我们递归地解决问题,从外到内地解决问题。
于是本题的解题思路如下:
* 1.初始化一个堆栈,并初始化一个映射表(用来处理不同种类的括号);
* 2.循环处理所有括号
* 如果是开括号,则push进栈即可;
* 如果是闭括号,那么就需要检查栈顶的元素,如果栈顶的开括号与当前的闭括号匹配(通过查找建立的映射表匹配),则pop出栈;如果不匹配,说明表达式无效;
- 3.当处理完所有括号后,如果栈中还有元素,说明表达式无效。
就想在玩一个消消乐,只有当开括号和闭括号匹配的时候才能消掉这一对括号。
Tips
栈
一种线性存储表。它有以下两种特性:
- 栈中数据按照后进先出(last-in, first-out, LIFO)的方式进栈和出栈的。
- 只能从栈顶(top)操作数据。
我们可以把它想象成几个盘子堆在弹簧上的场景。

图4:栈的结构示意图
**入栈(push)**

图5:入栈示意图
**出栈(pop)**

图6:出栈示意图
C++
bool isValid(string s) {
map<char,char> table={ {')', '('}, {']', '['}, {'}', '{'} };
if( s.size()== 0 )
return true;
stack<char> cStack;
for(int i = 0;i<s.size(); i++){
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
cStack.push(s[i]);
else if(s[i] == ')' || s[i] == ']' || s[i] == '}'){
if(cStack.empty())
return false;
char popChar = cStack.top();
if(popChar == table[s[i]]){
cStack.pop();
continue;
}
else
return false;
}
}
if(cStack.empty())
return true;
return false;
}
Python
20. Valid Parentheses[E]有效的括号的更多相关文章
- 《LeetBook》leetcode题解(20):Valid Parentheses[E]——栈解决括号匹配问题
我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...
- [Leetcode][Python]20: Valid Parentheses
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 20: Valid Parentheseshttps://oj.leetcod ...
- leetcode 20. Valid Parentheses 、32. Longest Valid Parentheses 、
20. Valid Parentheses 错误解法: "[])"就会报错,没考虑到出现')'.']'.'}'时,stack为空的情况,这种情况也无法匹配 class Soluti ...
- LeetCode解题笔记 - 20. Valid Parentheses
这星期听别人说在做LeetCode,让他分享一题来看看.试了感觉挺有意思,可以培养自己的思路,还能方便的查看优秀的解决方案.准备自己也开始. 解决方案通常有多种多样,我觉得把自己的解决思路记录下来,阶 ...
- leetCode练题——20. Valid Parentheses
1.题目 20. Valid Parentheses——Easy Given a string containing just the characters '(', ')', '{', '}', ...
- 刷题20. Valid Parentheses
一.题目说明 这个题目是20. Valid Parentheses,简单来说就是括号匹配.在学数据结构的时候,用栈可以解决.题目难度是Medium. 二.我的解答 栈涉及的内容不多,push.pop. ...
- 20. Valid Parentheses【leetcode】
20. Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', ...
- [LeetCode] 20. Valid Parentheses 验证括号
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
- [leetcode]20. Valid Parentheses有效括号序列
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
随机推荐
- QS之force(2)
Examples 1) Force input1 to 0 at the current simulator time. force input1 0 2) Force the fourth elem ...
- jQuery顺序加载图片(终版)
这一篇是对上一篇(jQuery顺序加载图片(初版)--http://www.cnblogs.com/newbie-cc/p/3707504.html)的改进. function loadImage(i ...
- spring中的prop、set、list、map
props.set.list.map这些事spring配置文件中很常见的标签,下面说下各自的适用场合. props:用于键值对,建和值都为string类型. <property name=&qu ...
- bootstrap 模态框日期控件datepicker被遮住问题的解决
找到日期输入框,并将 .class 属性的 z-index 改大 在JSP页添加样式: 这样就OK了:
- Monad (functional programming)
In functional programming, a monad is a design pattern that defines how functions, actions, inputs, ...
- mac 上执行 rm -rf /
# 很可怕的指令,清空磁盘所有资料,千万不要用 sudo 尝试,吓的小心肝差掉跳出来 rm -rf / 无聊,想执行rm -rf /会怎样,想起没加sudo时对~/download执行提示权限不足,被 ...
- 与Java注释相关的一些知识
* Html标签: * <a> 可定义锚,主要有以下两种属性 * href(最重要):创建指向另外一个文档的链接(或超链接) * ...
- 6——Z 字形变换(ZigZag Conversion)
题目描述将一个给定字符串根据给定的行数,以从上往下.从左到右进行 Z 字形排列. 比如输入字符串为 “LEETCODEISHIRING” 行数为 3 时,排列如下: L C I RE T O E S ...
- Javaweb 使用Servlet技术改写用户登录 使用Filter技术解决中文乱码
先把实验3的jsp页面复制过来: WebContent->WEB-INF->lib下面的jar包8.0版本也要记得复制: Java Resources->src下的 cn.edu.h ...
- BZOJ2251 [2010Beijing Wc]外星联络 后缀数组 + Height数组
Code: #include <bits/stdc++.h> #define setIO(s) freopen(s".in", "r", stdin ...