一、题目要求
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.
二、代码实现
bool isValid(string s) {
stack<char> st;
if(s.empty())
return true;
for(auto tmp=s.begin();tmp!=s.end();tmp++)
{
if(st.empty())
st.push(*tmp);
else
{
if((*tmp==')'&&st.top()=='(')||(*tmp==']'&&st.top()=='[')||(*tmp=='}'&&st.top()=='{'))
st.pop();
else
st.push(*tmp);
}
}
//
if(st.empty())
return true;
else
return false;
}