LeetCode 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.
bool isValid(string s)
{
if(s.length()==1)
return false;
stack<char> sta;
for(int i=0; i<s.length(); i++)
{
if(s[i] == '(' || s[i]=='{' || s[i]=='[')
sta.push(s[i]);
else if(sta.size()!=0 && ((sta.top()=='('&&s[i]==')') || (sta.top()=='['&&s[i]==']') || (sta.top()=='{'&&s[i]=='}')))
{
sta.pop();
}
else
return false;
}
if(sta.size() ==0)
return true;
else
return false;
}