题目:
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();//假如出现“()”,没有这句话,就会没有数值输出
}
};