Valid Parentheses
来源:互联网 发布:无限网络 封优酷 编辑:程序博客网 时间:2024/05/29 08:03
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>stack;for (int i = 0; i < s.size(); ++i){if (s[i] == '(' || s[i] == '[' || s[i] == '{'){stack.push(s[i]);continue;}if (!stack.empty()){char c = stack.top();switch (s[i]){case ')':{if (c == '('){stack.pop();break;}elsereturn false;}case ']':{if (c == '['){stack.pop();break;}elsereturn false;}case '}':{if (c == '{'){stack.pop();break;}elsereturn false;}default:break;}}elsereturn false;}if (!stack.empty())return false;return true;}};
0 0
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- 2016/3/14 开始自己的编程之路
- java实现走迷宫
- 统计难题
- LeetCode题解-6. ZigZag Conversion
- 关于代理、通知和KVO区别
- Valid Parentheses
- python show-me-the-code 第0004
- Android中5大数据存储(一)---SharedPreferences存储
- 在vs2008中怎么把一个项目复制到另一个项目中
- maven 快照
- 找出21位的水仙数
- Android 自定义流式布局
- java代码实现mongodb故障迁移和读写分离
- Jsp到Action后台的数据接收方法