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.
在dicussion中看到的思想:使用stack来进行字符串匹配,联想,与编译原理中使用堆栈来进行语法分析同理操作!!!
C++:
#include <stack>
class Solution {
public:
bool isValid(string s) {
stack<char> stacklist;
for(char& c : s){
switch(c){
case '(':
case '[':
case '{':stacklist.push(c);break;
case ')':
if(stacklist.empty()||stacklist.top()!='(')
return false;
else
stacklist.pop();
break;
case ']':
if(stacklist.empty()||stacklist.top()!='[')
return false;
else
stacklist.pop();
break;
case '}':
if(stacklist.empty()||stacklist.top()!='{')
return false;
else
stacklist.pop();
break;
default: ;
}
}
return stacklist.empty();
}
};