http://oj.leetcode.com/problems/valid-parentheses/
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.
思路:用stack来模拟。注意判断stack是否为空。
参考代码:SECOND TRIAL OVERLOAD THE FIRST.
class Solution {
public:
bool isValid(string s) {
if(s.empty())
return true;
stack<char>st;
for(int i = 0; i<s.length(); ++i)
{
if(s[i]=='(' || s[i]=='[' || s[i]=='{')
st.push(s[i]);
else if(s[i]==')')
{
if(!st.empty() && st.top()=='(')
st.pop();
else
return false;
}
else if(s[i]==']')
{
if(!st.empty() && st.top()=='[')
st.pop();
else
return false;
}
else if(s[i]=='}')
{
if(!st.empty() && st.top()=='{')
st.pop();
else
return false;
}
}
return st.empty();
}
};