Leetcode 20. Valid Parentheses
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.
class Solution {
public:bool isValid(string s) {
stack<char> st;
for (char c:s)
{
if (c == '(') st.push(c);
if (c == '{') st.push(c);
if (c == '[') st.push(c);
if (c == ')')
{
if (st.empty() || st.top() != '(') return false;
else st.pop();
}
if (c == '}')
{
if (st.empty() || st.top() != '{') return false;
else st.pop();
}
if (c == ']')
{
if (st.empty() || st.top() != '[') return false;
else st.pop();
}
}
return st.empty();
}
};
参考Discuss中头名代码后,他的思路是当遇到括号左半部分,将右半部分压栈,这样当遇到右半部分直接与栈顶值比较就可,这样在分类时不需要针对左半部分区别右半部分的具体形式,只需要自己跟自己比较是否相等,代码简洁程度大大提高。
修改后如下:
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for (char c:s)
{
if (c == '(') st.push(')');
else if (c == '{') st.push('}');
else if (c == '[') st.push(']');
else
{
if (st.empty() || c != st.top())
return false;
else st.pop();
}
}
return st.empty();
}
};
注意:if (st.empty() || c != st.top())中两个判断条件的顺序不能错,因为当第一个括号不符合时,先判断c != st.top()会出错,因为st.top()没东西。