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.
Code:
bool isValid(string str) {
size_t n = str.length();
stack<char>s;
for (int i = 0; i < n; ++i)
{
//要注意及时检查栈是否为空,因为不能对空栈调用top函数
if (s.empty() || str[i] == '(' || str[i] == '{' || str[i] == '[')
s.push(str[i]);
else
{
char c = s.top();
if ( (c== '(' && str[i] == ')')
|| (c== '[' && str[i] == ']')
|| (c== '{' && str[i] == '}') )
s.pop();
else
return false;
}
}
return (s.empty()==true)?true:false;
}