【一天一道LeetCode】#20. Valid Parentheses
2016-04-17 22:03
381 查看
一天一道LeetCode系列
(一)题目
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.
(二)解题
本题的关键在于利用stack,想到了stack就不难写出代码了。每次碰到(,{,[就压栈,碰到),},],就判断栈顶元素匹配上就出栈,匹配不上就返回false.
下面是Accepted的代码,复杂度为0(n):
class Solution { public: bool isValid(string s) { stack<char> tmp; for(int i = 0 ; i < s.length() ; i++) { if(s[i] == '(' || s[i] == '{' || s[i] == '[') { tmp.push(s[i]); } else if(s[i] == ')' || s[i] == '}' || s[i] == ']') { if(tmp.empty()) return false; switch(s[i]) { case ')': if(tmp.top() == '(') tmp.pop(); else return false; break; case ']': if(tmp.top() == '[') tmp.pop(); else return false; break; case '}': if(tmp.top() == '{') tmp.pop(); else return false; break; } } } if(tmp.empty()) return true; else return false; } };
相关文章推荐
- 博弈论——尼姆博奕
- 【一天一道LeetCode】#20. Valid Parentheses
- 模拟实现strcmp、strcat、strstr
- Swift: Tuple 元组
- 【ATF】林伟:大数据计算平台的研究与实践
- 20145310《Java程序设计》第2次实验报告
- Java之类型的转换
- java.sql.Types,数据库字段类型,java数据类型的对应关系
- NSTimer内存方面的探究
- ubuntu 14LTS中文输入法安装
- 不借助第三个变量实现两个变量交换
- HttpClient 4.3教程(转载)
- Alibaba Dubbo框架同步调用原理分析-2
- 魏佐夫博弈HDU1527
- HDU1301 最小生成树 + Prim +(Prim求最小生成树与Dijkstra求最短路的区别) (如此题不要误解题意为用Dijkstra!)
- 通过JS语句判断WEB网站的访问端是电脑还是手机
- 第四周项目四(4)-程序分析
- Linux五种IO模型
- Android 使用RadioGroup和RadioButton实现单选效果
- CentOS 7下编译安装 nginx1.9.14