Valid Parentheses
来源:互联网 发布:最好的大六壬排盘软件 编辑:程序博客网 时间:2024/05/29 08:07
题目:
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.
思路:
遇到 “(” “{” “[”,进入堆栈;
如果不是,查看堆栈中是否为空,为空,false。
不为空,查看顶端字符与当前字符是否配对,并出栈。
代码:
class Solution {public: bool isValid(string s) { if(s.empty()) return false; int len=s.length(); stack<char>stk; for(int i=0;i<len;i++){ if(s[i]=='['||s[i]=='{'||s[i]=='('){ stk.push(s[i]); }else{ if(stk.empty()){ return false; }else if(stk.top()=='{'&&'}'==s[i]){ stk.pop(); }else if(stk.top()=='['&&']'==s[i]){ stk.pop(); }else if(stk.top()=='('&&')'==s[i]){ stk.pop(); }else return false; } } 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
- 使用FreeImage写通用图像加载器
- E-R图设计的步骤
- pAdTy_4 构建有联系人和签署的应用程序
- DOM 对象控制 HTML
- 实战c++中的vector系列--构造、operator=和assign区别
- Valid Parentheses
- Unity3D 把代码混淆过的代码返混淆回来
- LogCat中没有信息显示:device disconnected:1
- JS代码整理
- FreeImage通用文件加载与转换器
- AndroidStudio导出Jar包
- AdaGrad理解错误更正
- ps_3_0 does not allow textures or samplers to be members of compound types
- HDU 2870 Largest Submatrix (求最大子矩阵变形,可变值)枚举每种情况