问题:链接
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(int i = 0; i < s.length(); ++i)
{
if(st.empty())
st.push(s[i]);
else if((st.top() == '[' && s[i] == ']') || (st.top() == '{' && s[i] == '}') || (st.top() == '(' && s[i] == ')'))
st.pop();
else
st.push(s[i]);
}
if(st.empty())
return true;
return false;
}
};