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.
判断括号是否匹配。
创建一个栈,依次遍历字符串,碰到 ’(','[','{'入栈,碰到 ’)',']','}'后,若栈空或者栈顶元素不为对应的右括号,则说明括号不匹配,返回false,遍历字符串结束后,栈为空,说明括号全部成对匹配,返回true。
AC代码:
class Solution {
public:
bool isValid(string s)
{
stack<char> stck;
int len = s.length();
for (int i = 0; i < len; i++)
{
switch (s[i])
{
case '(':
stck.push(s[i]);
break;
case '[':
stck.push(s[i]);
break;
case '{':
stck.push(s[i]);
break;
case ')':
if (stck.empty() || stck.top() != '(')
return false;
else
stck.pop();
break;
case ']':
if (stck.empty() || stck.top() != '[')
return false;
else
stck.pop();
break;
case '}':
if (stck.empty() || stck.top() != '{')
return false;
else
stck.pop();
break;
}
}
if (stck.empty())
return true;
else
return false;
}
};