description: 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> charStack;
int i=0;
while(i!=s.length()){
char c=s[i];
if(c!=')'&&c!=']'&&c!='}'){
charStack.push(c);
}
else{
if(charStack.size()==0) return false;
char d=charStack.top();
switch(c){
case ')':
if(d=='(') charStack.pop();
else return false;
break;
case ']':
if(d=='[') charStack.pop();
else return false;
break;
case '}':
if(d=='{') charStack.pop();
else return false;
break;
}
}
i++;
}
if(charStack.size()==0) return true;
else return false;
}
};