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.
栈操作,匹配栈顶即可!
在出栈、取值等操作之前,先用empty() 判断一下是否为空!
不要炫技,较多的逻辑判断,用多行,保证可读性!简单程序更快、安全、易于调试!
class Solution {
public:
bool isValid(string s) {
if(s.size() == 0)return false;
int len = s.size();
stack<char> stk;
for(int i = 0; i < len; i++)
{
if(s[i] =='{' || s[i] == '[' || s[i] == '(')
stk.push(s[i]);
else
{
if(stk.empty())return false;
if((s[i] == '}' && stk.top() == '{')
|| (s[i] == ']' && stk.top() == '[')
|| (s[i] == ')' && stk.top() == '('))
stk.pop();
else return false;
}
}
return stk.empty();
}
};