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.
其实是括号匹配问题,用栈来实现比较方便.
//3ms AC
class Solution {
public:
bool isValid(string s) {
int len = s.length();
if(len%2 == 1)
return false;
stack<char> symbol;
for(int i=0;i<len;i++)
{
if(s[i]=='(' || s[i]=='{' || s[i]=='[')
{
symbol.push(s[i]);
}
else //右括号
{
if(symbol.empty()) //栈为空,肯定不匹配
{
return false;
}
switch(s[i])
{
case ')':{
if(symbol.top() != '(')
return false;
break;
}
case ']':{
if(symbol.top() != '[')
return false;
break;
}
case '}':{
if(symbol.top() != '{')
return false;
break;
}
default:
break;
}
symbol.pop();
}
}
if(symbol.empty())
return true;
else
return false;
}
};