20. Valid Parentheses
来源:互联网 发布:ps绘画软件 编辑:程序博客网 时间:2024/04/30 23:25
题目描述:
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.
思路分析:检验括号是否是匹配的,我们使用一个栈来解决。有三种错误情况:字符串为空;右括号匹配错误(不同符号或匹配空栈);左括号没有匹配。
所以我们的算法思路就是先判断字符串长度,然后开始入栈,如果为“(”、“[”和“{”等左括号的话就进栈,然后看下一个字符是否匹配,不匹配就返回false,匹配就出栈。最后检查所有元素是否出栈。
代码:
class Solution {public: bool isValid(string s) { stack<char> stk; if(s.length()%2 != 0)//odd number of chars can not be valid return false; for(int i = 0; i < s.length(); i++){ if(s[i] == '(' || s[i] == '[' || s[i] == '{') stk.push(s[i]); if(s[i] == ')' && (stk.empty() || stk.top() != '('))//false circumstances return false; if(s[i] == ']' && (stk.empty() || stk.top() != '[')) return false; if(s[i] == '}' && (stk.empty() || stk.top() != '{')) return false; if(s[i] == ')' && stk.top() == '(')//valid circumstance stk.pop(); if(s[i] == ']' && stk.top() == '[') stk.pop(); if(s[i] == '}' && stk.top() == '{') stk.pop(); } return stk.empty();// the stack is empty means validness. }};时间复杂度:O(n) //n为字符串长度
反思:做的时候很没有思路,错了无数遍,希望以后做题把所有情况都考虑完整的,不要多次submit。开始的判断奇数其实没有必要,提升了一丢丢性能罢了。
阅读全文
0 0
- LeetCode 20. Valid Parentheses
- [LeetCode] 20.Valid Parentheses
- LeetCode --- 20. Valid Parentheses
- LeetCode 20.Valid Parentheses
- [Leetcode] 20. Valid Parentheses
- 20.Valid Parentheses
- 20.Valid Parentheses
- 20. Valid Parentheses
- 【leetcode】20. Valid Parentheses
- [leetcode] 20.Valid Parentheses
- [leetcode] 20. Valid Parentheses
- 20. Valid Parentheses
- 20. Valid Parentheses
- 20. Valid Parentheses
- Leetcode 20. Valid Parentheses
- 20. Valid Parentheses LeetCode
- 20. Valid Parentheses
- 20. Valid Parentheses
- 拆解iPhone X,豪门云集的内部设计是否让你值回票价?
- 吸引工信部部长参与试乘的图森未来,拟在明年进行自动驾驶车队的测试
- Bengio等人提出图注意网络架构GAT,可处理复杂结构图
- 取代学习率衰减的新方法:谷歌大脑提出增加Batch Size
- 先读懂CapsNet架构然后用TensorFlow实现:全面解析Hinton的提出的Capsule
- 20. Valid Parentheses
- Matlab 将多个子函数写到一个m文件中
- Android样式的开发
- Xcode9学习笔记36
- 配置Eclipse编写HTML/JS/CSS/JSP页面的自动提示
- 我们计划为EasyDSS定制开发一款超低延时的EasyPlayer Flash播放器
- WIN10下安装MYSQL5.5.55时最后出现“mysql server instance configuration wizard未响应”
- 倍增法求LCA
- IntelliJ IDEA中文乱码问题