[leetcode] 20. Valid Parentheses
来源:互联网 发布:jquery封装json 编辑:程序博客网 时间:2024/06/07 00:10
Question:
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.
Solution:
利用栈的特性,对于合法的括号,右括号的出现则要检查栈顶是否为对应的左括号,是则将栈顶元素弹出,继续检查下一个括号。这样做就能检查一对括号中夹着若干对其他括号,从最里面的一对括号开始检查。若最后栈为空,则说明所有括号均是合法的。
时间复杂度:O(n)
空间复杂度:O(n)
class Solution {public: bool isValid(string s) { stack<char> st; for (int i = 0; i < s.size(); i++) { if (st.empty()) { st.push(s[i]); } else if (s[i] == ']' && st.top() == '[') { st.pop(); } else if (s[i] == ')' && st.top() == '(') { st.pop(); } else if (s[i] == '}' && st.top() == '{') { st.pop(); } else { st.push(s[i]); } } if (st.empty()) return true; return false; }};
阅读全文
0 0
- LeetCode 20. Valid Parentheses
- [LeetCode] 20.Valid Parentheses
- LeetCode --- 20. Valid Parentheses
- LeetCode 20.Valid Parentheses
- [Leetcode] 20. Valid Parentheses
- 【leetcode】20. Valid Parentheses
- [leetcode] 20.Valid Parentheses
- [leetcode] 20. Valid Parentheses
- Leetcode 20. Valid Parentheses
- 20. Valid Parentheses LeetCode
- leetcode 20. Valid Parentheses
- 【LeetCode】20. Valid Parentheses
- leetcode 20. Valid Parentheses
- leetcode 20. Valid Parentheses
- LeetCode-20.Valid Parentheses
- LeetCode *** 20. Valid Parentheses
- LeetCode 20. Valid Parentheses
- leetcode-20. Valid Parentheses
- HybridDB · 最佳实践 · 阿里云数据库PetaData
- robotframework关键字
- 小程序逻辑层
- Mongodb亿级数据量的性能测试
- 如何在同一台机器上安装运行多个Tomcat
- [leetcode] 20. Valid Parentheses
- HTML表单和组件
- 数据库相关异常
- css去除文本框偶然出现的选中蓝色底问题
- 免费的编程中文书籍索引
- 系统化思维-公司培训
- CAD转换技巧之cad如何转换成图片经验分享
- leetcode问题解答:23. Merge k Sorted Lists
- mysql事务隔离级别