Valid Parentheses
2015-12-15 20:51
330 查看
题目:
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();//假如出现“()”,没有这句话,就会没有数值输出
}
};
相关文章推荐
- Java 大作业 个人通讯录的实现
- android 全屏对话框
- igs08核心站
- FreeImage通用文件加载与转换器
- mysql导入sql文件
- python安装mysql库
- AndroidStudio导出Jar包
- 动画(Animation) 、 高级动画(Core Animation)
- offload error: cannot find offload entry解决办法
- offload error: cannot find offload entry解决办法
- 实战c++中的vector系列--构造、operator=和assign区别
- 实战c++中的vector系列--构造、operator=和assign区别
- 关于基类析构函数的问题 http://bbs.csdn.net/topics/390543618
- 使用FreeImage写通用图像加载器
- Oracle执行计划
- win10 python nltk安装
- Mousetrap - Keyboard shortcuts in Javascript
- DOM 对象控制 HTML
- oracle视图
- pAdTy_4 构建有联系人和签署的应用程序