[LeetCode 20]
Description
Description
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) {
int top=0;int i=1;
int length = strlen(s);
char stack[length];
if(length == 0 | length == 1) return 0;
for(i=0;i<strlen(s);i++){
if(top == 0){
stack[0] = s[i];
top ++;
continue;
}
switch(stack[top - 1]){
case '(':
if( s[i] == '{' || s[i] == '[' || s[i] == '(' ){
stack[top]=s[i];
top ++;
}
else if(s[i] == ')') top--;
else return 0;
break;
case '[':
if( s[i] == '{' || s[i] == '[' || s[i] == '(' ){
stack[top]=s[i];
top ++;
}
else if(s[i] == ']') top--;
else return 0;
break;
case '{':
if( s[i] == '{' || s[i] == '[' || s[i] == '(' ){
stack[top]=s[i];
top ++;
}
else if(s[i] == '}') top--;
else return 0;
break;
}
}
if(!top) return 1;
else return 0;
}