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> S;
int n = s.length();
for(int i = 0; i < n; i++)
{
if(s[i] == '(' || s[i] == '{' || s[i] == '[')S.push(s[i]);
else if (s[i] == ')' || s[i] == '}' || s[i] == ']')
{
if(S.empty())return false;
char t = S.top();
S.pop();
if((s[i] == ')' && t!= '(') ||
(s[i] == '}' && t!= '{') ||
(s[i] == ']' && t!= '[') )return false;
}
}
if(!S.empty())return false;
return true;
}
No comments:
Post a Comment