题目描述:
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.
需要注意的是栈为空时,若s[i]为右括号则返回false。
代码:
class Solution {
public:
bool isValid(string s) {
if (s.length() % 2 == 1)
return false;
stack<char> chars;
for (int i = 0; i < s.length(); i++){
if (s[i] == '(')
chars.push(')');
else if (s[i] == '[')
chars.push(']');
else if (s[i] == '{')
chars.push('}');
else if (!chars.empty() && s[i] == chars.top())
chars.pop();
else
return false;
}
if (chars.empty())
return true;
return false;
}
};