您的位置:首页 > 其它

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();//假如出现“()”,没有这句话,就会没有数值输出
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: