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.
Tag: 栈
bool isValid(string s)
{
std::stack<char> st;
for(int i = 0; i < s.size(); i++)
{
if(s[i] == '(' || s[i] == '{' || s[i] == '[')
{
st.push(s[i]);
continue;
}
switch(s[i])
{
case ')':
if(st.empty() || st.top() != '(')
{
return false;
}
else
{
st.pop();
}
continue;
case '}':
if(st.empty() || st.top() != '{')
{
return false;
}
else
{
st.pop();
}
continue;
case ']':
if(st.empty() || st.top() != '[')
{
return false;
}
else
{
st.pop();
}
continue;
}
}
if(st.empty())
return true;
else
return false;
}