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(char *s) {
const int size = 10000;
char stack[size];
int p = 0;
for (; *s != '\0'; ++s) {
switch (*s) {
case ')':
if (p == 0 || stack[p - 1] != '(') {
return false;
}
--p;
break;
case ']':
if (p == 0 || stack[p - 1] != '[') {
return false;
}
--p;
break;
case '}':
if (p == 0 || stack[p - 1] != '{') {
return false;
}
--p;
break;
default:
stack[p++] = *s;
} // switch
}
return p == 0;
}