[LeetCode]Valid Parentheses
来源:互联网 发布:淘宝网春秋女装 编辑:程序博客网 时间:2024/06/05 07:07
Q: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.
这道题是括号匹配问题,考察的是栈的基本使用。
我定义了一个括弧的优先级表,若当前字符优先级大于栈顶字符(1),则弹出栈顶字符;若当前字符优先级小于栈顶字符(0),则当前字符入栈。最后观察栈是否为空,若为空,则括弧配对,否则不配对。优先级表如下图:
下面贴上代码:
#include <iostream>#include<stack>using namespace std;class Solution {public:int replace(char c){if (c == '(')return 0;if (c == ')')return 1;if (c == '[')return 2;if (c == ']')return 3;if (c == '{')return 4;if (c == '}')return 5;}bool isValid(string s) {if (s.length() == 0 || s.length() == 1)return false;int ch[6][6] = { { 0, 1, 0, 0, 0, 0 },{ 0, 0, 0, 0, 0, 0 },{ 0, 0, 0, 1, 0, 0 },{ 0, 0, 0, 0, 0, 0 },{ 0, 0, 0, 0, 0, 1 },{ 0, 0, 0, 0, 0, 0 }};stack<char> ss;for (int i = 0; i < s.length(); i++){if (ss.empty()){ss.push(s[i]);continue;}char c = ss.top();if (ch[replace(c)][replace(s[i])])ss.pop();elsess.push(s[i]);}if (ss.empty())return true;elsereturn false;}};int main() {Solution s;cout << s.isValid("()[]{}()") << endl;cout << s.isValid("(([]{}))") << endl;cout << s.isValid("([]}") << endl;return 0;}
0 0
- LeetCode: Valid Parentheses
- LeetCode: Longest Valid Parentheses
- LeetCode: Valid Parentheses
- LeetCode Longest Valid Parentheses
- [Leetcode] Valid Parentheses
- LeetCode: Longest Valid Parentheses
- [Leetcode] Longest Valid Parentheses
- LeetCode : Valid Parentheses
- [leetcode]longest Valid Parentheses(!!)
- Leetcode: Valid Parentheses
- leetcode 52: valid parentheses
- [Leetcode] Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- 【leetcode】Valid Parentheses
- 【leetcode】Longest Valid Parentheses
- [LeetCode]Longest Valid Parentheses
- [LeetCode]Valid Parentheses
- LeetCode-Valid Parentheses
- NYOJ表达式求值
- Swift游戏开发之俄罗斯方块:No.8 游戏规则
- 使用新浪微博sdk开发
- 计算机网络协议第八章,TCP协议基础
- Linux0.11内核源代码(2)
- [LeetCode]Valid Parentheses
- poj3484
- java编程思想第四版习题_8.3
- iOS-基本数据类型-NSString
- 拓扑排序
- Merge Two Sorted Lists - LeetCode
- 新浪sdk说明
- linux 0号进程 1号进程 区别(转)
- HDOJ 2035 人见人爱A^B(快速幂取余)