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.Solution:
bool isValid(string s, int& cur, stack<char>& left)
{
if(cur == s.size())
{
if(left.empty())
return true;
else
return false;
}
bool flag = true;
if(s[cur]=='('||s[cur]=='['||s[cur]=='{')
{
left.push(s[cur]);
}
else
{
if(left.empty())
flag = false;
else if((s[cur]==')'&&left.top()=='(')||(s[cur]==']'&&left.top()=='[')||(s[cur]=='}'&&left.top()=='{'))
left.pop();
else
flag = false;
}
cur++;
if(flag)
return isValid(s, cur,left);
else
return false;
}
bool isValid(string s) {
int cur=0;
stack<char> left;
return isValid(s, cur, left);
}
No comments:
Post a Comment