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>stack;
for (int i = 0; i < s.size(); ++i){
if (s[i] == '(' || s[i] == '[' || s[i] == '{'){
stack.push(s[i]);
continue;
}
if (!stack.empty()){
char c = stack.top();
switch (s[i]){
case ')':
{
if (c == '(')
{
stack.pop();
break;
}
else
return false;
}
case ']':
{
if (c == '[')
{
stack.pop();
break;
}
else
return false;
}
case '}':
{
if (c == '{')
{
stack.pop();
break;
}
else
return false;
}
default:
break;
}
}
else
return false;
}
if (!stack.empty())
return false;
return true;
}
};