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.
My C++ solution!
bool isValid(string s)
{
int len=s.length();
if(len%2)
return false;
stack<char> st;
int i=1;
st.push(s[0]);
while(i<len)
{
if(st.empty())
st.push(s[i]);
else
{
if(s[i]-st.top()>2||s[i]-st.top()<1)
st.push(s[i]);
else
st.pop();
}
i++;
}
return st.size()==0?true:false;
}