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 ...
随机推荐
- Assembly之instruction之Indirect Autoincrement Mode
Assembler Code Content of ROMMOV @R10+,0(R11) MOV @R10+,0(R11) Length: One or two words Operation: ...
- 红黑联盟 php相关资讯
http://www.2cto.com/tag/phpbanben.html
- Android读写文件
1.从resource中的raw文件夹中获取文件并读取数据(资源文件只能读不能写) String res = ""; try{ InputStream in = getResour ...
- [Intermediate Algorithm] - Arguments Optional
题目 创建一个计算两个参数之和的 function.如果只有一个参数,则返回一个 function,该 function 请求一个参数然后返回求和的结果. 例如,add(2, 3) 应该返回 5,而 ...
- (转)Arcgis for JS之对象捕捉
http://blog.csdn.net/gisshixisheng/article/details/44098615 在web操作,如绘制或者测量的时候,为了精确,需要捕捉到某一图层的对象,在此,讲 ...
- jquery.datatable.js实际运用
$.dataTablesSettings = { deferRender: true,// 当处理大数据时,延迟渲染数据,有效提高Datatables处理能力 bStateSave: true,//表 ...
- springboot 大致启动流程
SpringApplication的run方法的实现是我们本次旅程的主要线路,该方法的主要流程大体可以归纳如下: 1) 如果我们使用的是SpringApplication的静态run方法,那么,这个方 ...
- mysql与oracle 表字段定义比较
链接: https://blog.csdn.net/yzsind/article/details/7948226
- PAT_A1141#PAT Ranking of Institutions
Source: PAT A1141 PAT Ranking of Institutions (25 分) Description: After each PAT, the PAT Center wil ...
- python写入Excel
一.dataframe存入Excel中: 注意:openpyxl打开的文件需是xlsx的后缀,因为比较新的. from openpyxl import load_workbook import pan ...