第四周Valid Parentheses
来源:互联网 发布:java 时间转时间戳 编辑:程序博客网 时间:2024/06/17 03:25
Valid Parentheses验证括号
Leetcode algorithms problem 20: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.问题提示
无
思路
利用一个栈保存左边的符号,遇到匹配的右符号就将栈顶弹出,最后检测栈是否为空。
代码
class Solution {public: bool isValid(string s) { stack<char> brackets; for(int i = 0; i < s.size(); i++) { if(s[i] == 40 || s[i] == 91 || s[i] == 123) { brackets.push(s[i]); } else { if(brackets.size() == 0) { return false; } char temp = brackets.top(); brackets.pop(); if(s[i] == 41 ) { if(temp != 40) { return false; } } else if(s[i] == 93 || s[i] == 125) { if(temp != (s[i] - 2)) { return false; } } } } return (brackets.size() == 0); }};
时间复杂度: O(n)
空间复杂度: O(n)
疑难及解决
一开始忘记考虑只有右边括号的情况,导致测试)】}实例时会报runtime error的错误(因为此时栈为空,栈的top及pop函数会出错),折腾了很久才发现,在第一个else部分判断栈是否为空就好了。
阅读全文
0 0
- 第四周Valid Parentheses
- 第29题 Valid Parentheses
- 第51题 Longest Valid Parentheses
- Leetcode 第20题 Valid Parentheses
- LeetCode第20题之Valid Parentheses
- valid parentheses leetcode 第20题
- leetcode 第20题<Valid Parentheses>(java)
- leetcode 第20-21题 Valid Parentheses & Generate Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- JVM (PART VI)垃圾收集算法
- typecho安装后登录失败报错 405 Not Allowed nginx/1.10.2
- kuangbin带你飞:专题一 简单搜索 L
- uri,file,path互相转化
- 循环中setTimeout打印结果(使用闭包)
- 第四周Valid Parentheses
- 机器学习常见算法分类汇总
- NOIP 2014 飞扬的小鸟
- 大四生活02:秋招开始
- 【C#】winform软件UI设计模板
- 树规? bzoj4007 战争调度
- 计算机中位(bite),字节(Byte),字,字长的概念
- bzoj1937 [Shoi2004]Mst 最小生成树(KM)
- 005_HTML制作炫酷登录界面(CSS精灵图、背景图片局部显示)