LeetCode---(20)Valid Parentheses
来源:互联网 发布:淘宝客服骂人怎么处罚 编辑:程序博客网 时间:2024/06/03 22:56
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、从前向后扫描字符串;
2、遇到左括号x,就压栈x;
3、遇到右括号y:
如果发现栈顶元x和该括号y匹配,则栈顶元素出栈,继续判断下一个字符;
如果栈顶元素x和该括号y不匹配,字符串不匹配;
如果栈为空,字符串不匹配;
4、扫描完成后,如果栈恰好为空,则字符串匹配,否则,字符串不匹配。
解法1:
class Solution {public: bool isValid(string s) { stack<char> stk; for(int i=0;i<s.size();i++) { char c=s[i]; if(c=='('||c=='{'||c=='[') stk.push(c); else{ if(stk.size()==0) return false; char pre=stk.top(); switch(c) { case ')': if(pre=='(') stk.pop(); else return false; break; case ']': if(pre=='[') stk.pop(); else return false; break; case '}': if(pre=='{') stk.pop(); else return false; break; } } } if(stk.empty()) return true; else return false; }};
解法2:
class Solution {public: bool isValid(string s) { string left="([{"; string right=")]}"; stack<char> stk; for(auto c:s) { if(left.find(c)!=string::npos) stk.push(c); else{ if(stk.empty()||stk.top()!=left[right.find(c)]) return false; else stk.pop(); } } if(stk.empty()) return true; else 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
- [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
- 分布式和集群区别
- LocalBroadcastManager使用简析
- kdtable回车键光标移动
- DUMPBIN命令使用详解
- 21. 多人协作
- LeetCode---(20)Valid Parentheses
- Behavioral模式之Chain of Responsibility模式
- 前缀、中缀、后缀表达式
- linux可用内存的计算
- bash下的特殊符号与通配符
- [Code] 《JS权威指南》示例程序 -- Loan Calculator
- ARM基础知识
- Object.wait()与Object.notify()的用法
- java 集合篇