Valid Parentheses
来源:互联网 发布:无法连接至steam网络 编辑:程序博客网 时间:2024/06/11 04:20
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>stk;
for(int i = 0; i < s.length(); ++i)
if(s[i] == '(' || s[i] == '[' || s[i] == '{')stk.push(s[i]);else//左括号存入栈内
if(s[i] == ')'){
if(stk.empty() || stk.top() != '(')return false;//栈内没有元素或者栈顶元素不匹配说明匹配失败,直接返回false,以下同
stk.pop();
}else
if(s[i] == ']'){
if(stk.empty() || stk.top() != '[')return false;
stk.pop();
}else
if(s[i] == '}'){
if(stk.empty() || stk.top() != '{')return false;
stk.pop();
}
return stk.empty();//如果为空说明匹配成功,否则说明还有多余左括号没匹配
}
};
主要应用了栈,将算法简化
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
- 从文件读入数据将其转化为2进制输出
- Tensorflow游乐场
- LeetCode Devide & Conquer || Search a 2D Matrix II
- Hibernate session
- 文章标题 动态规划理解(1)
- Valid Parentheses
- evaluate-reverse-polish-notation
- 策略模式(Strategy Pattern)
- jComboBox绑定数据库
- Android活动生命周期
- ECshop二次开发从开始
- PTA 一 长城
- Hash的应用
- UDP中的connect方法 和TCP的connect方法详解