leetcode解题报告(7):Valid Parentheses
描述
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
分析
遇到这种括号匹配的问题,当然要用栈来写。先把string的第一个元素压入栈,再从第二个元素开始遍历,如果栈顶元素为和当前string的元素相匹配,就把该元素出栈。如果在遍历期间堆栈为空了,比如输入的是:
[]{}()
那么在i=1的时候栈就会为空,这时候取栈顶元素是没有意义的。因此如果遍历期间发现栈为空,就直接把当前的string元素压入栈中。
另外,如果输入的string的长度不是偶数,那么肯定是不匹配的,在一开始的时候做这个判断,可以筛掉很多种不匹配的情况。
总之,如果输入的string是匹配的,那么最终的栈一定为空。
为了判断栈顶元素和当前string的元素是否相匹配,可以定义一个名为isOK的函数。
代码如下:
class Solution {
public:
bool isOK(const char &a,const char &b){
if((a == '(' && b == ')')
|| (a == '[' && b == ']')
|| (a == '{' && b == '}'))
return true;
else
return false;
}
bool isValid(string s) {
if(s.size() % 2 != 0)return false;
stack<char>sc;
sc.push(s[0]);
for(int i = 1; i != s.size(); ++i){
if(sc.empty())
sc.push(s[i]);
else{
if(isOK(sc.top(),s[i]))
sc.pop();
else
sc.push(s[i]);
}
}
return sc.empty();
}
};
下面是另一种更优雅的解法:
https://leetcode.com/problems/valid-parentheses/#/solutions
class Solution {
public:
bool isValid(string s) {
if(s.size() % 2 != 0)return false;
stack<char>paren;
for(char& c : s){
switch(c){
case '(':
case '[':
case '{':paren.push(c);break;
case ')':if(paren.empty() || paren.top() != '(')return false;paren.pop();break;
case ']':if(paren.empty() || paren.top() != '[')return false;paren.pop();break;
case '}':if(paren.empty() || paren.top() != '{')return false;paren.pop();break;
default:;
}
}
return paren.empty();
}
};
leetcode解题报告(7):Valid Parentheses的更多相关文章
- LeetCode解题报告—— Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- LeetCode解题笔记 - 20. Valid Parentheses
这星期听别人说在做LeetCode,让他分享一题来看看.试了感觉挺有意思,可以培养自己的思路,还能方便的查看优秀的解决方案.准备自己也开始. 解决方案通常有多种多样,我觉得把自己的解决思路记录下来,阶 ...
- LeetCode解题报告:Linked List Cycle && Linked List Cycle II
LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...
- 乘风破浪:LeetCode真题_032_Longest Valid Parentheses
乘风破浪:LeetCode真题_032_Longest Valid Parentheses 一.前言 这也是非常有意思的一个题目,我们之前已经遇到过两个这种括号的题目了,基本上都要用到堆栈来解决,这次 ...
- leetcode解题报告(2):Remove Duplicates from Sorted ArrayII
描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...
- leetcode解题报告 32. Longest Valid Parentheses 用stack的解法
第一道被我AC的hard题!菜鸡难免激动一下,不要鄙视.. Given a string containing just the characters '(' and ')', find the le ...
- LeetCode 解题报告索引
最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中...... ...
- 【一天一道LeetCode】#32. Longest Valid Parentheses
一天一道LeetCode系列 (一)题目 Given a string containing just the characters '(' and ')', find the length of t ...
- 【LeetCode练习题】Longest Valid Parentheses
Longest Valid Parentheses Given a string containing just the characters '(' and ')', find the length ...
- [Leetcode][Python]32: Longest Valid Parentheses
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 32: Longest Valid Parentheseshttps://oj ...
随机推荐
- STM32的I2C通讯过程
使用I2C外设通讯时,在通讯的不同阶段它会对“状态寄存器(SR1 及SR2)”的不同数据位写入参数,通过读取这些寄存器标志来了解通讯状态. 1.主发送器 可使用STM32标准库函数来直接检测这些事件的 ...
- SAS学习笔记20 CAT函数
- Sparse PCA 稀疏主成分分析
Sparse PCA 稀疏主成分分析 2016-12-06 16:58:38 qilin2016 阅读数 15677 文章标签: 统计学习算法 更多 分类专栏: Machine Learning ...
- MySQL 子查询(二)
接上篇文章,从这节起:MySQL 5.7 13.2.10.5 Row Subqueries 五.行子查询(ROW Subqueries) 标量子查询返回单个值,列子查询返回一个列的多个值.而行子查询是 ...
- Java RadixSort
Java RadixSort /** * <html> * <body> * <P> Copyright 1994-2018 JasonInternational ...
- Vibe
在读研和工作之间徘徊了半年,看着一个个好友工作.保研,生活安排得井井有条,我也是时候收拾心情,整装前进了.既然选择了图像,就一定要好好做下去. 今天开始第一个算法,Vibe. ViBe是一种像素级视频 ...
- mysql8中查询语句表别名不能使用 “of”
今天在迁移一个项目的时候,发现有一个sql报错,但是语句跟迁移之前完全一样,所以想来应该是 mysql 版本差异导致的. 迁移之前版本:5.6.28(腾讯云) 迁移之后版本:8.0.16(阿里云) 新 ...
- Unity 自定义"=="操作符 [翻译来源blogs.unity3d,2014/05]
主要内容来源 https://blogs.unity3d.com/cn/2014/05/16/custom-operator-should-we-keep-it/ 在我们代码里,如果有这样的代码: i ...
- ubuntu16下 Oracle安装完毕,测试是否安装成功的步骤
1.查看oracle的环境变量,在终端输入命令 echo $ORACLE_BASE echo $ORACLE_HOME echo $PATH 看输出是不是安装时设置的路径 2.开启监听器 lsnrct ...
- 注解@Slf4j使用
我们在写代码的时候需要加入日志打印,如果不想每次都写private final Logger logger = LoggerFactory.getLogger(XXX.class); 那么可以用注解 ...