题目:
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.
思路:利用栈后进先出的特点,例如:如果查找到字符串中‘}’,判断栈顶st.top 是不是‘{’,若不是,则返回false。若是,则st.pop(); 这样最后判断st.empty()即可;
class solution{
public:
bool isValid(string s) {
//栈 后进先出
stack<char>st;
for(int i=0;i<s.size();i++)
{
if(s[i]==')'||s[i]==']'||s[i]=='}')
{
if(st.empty())
return false;
else
{
char c=st.top();
st.pop();
if(c=='('&&s[i]!=')'||c=='['&&s[i]!=']'||c=='{'&&s[i]!='}')
{
return false;
}
}
}
else
{
st.push(s[i]);
}
}
return st.empty();
}
};