括號匹配
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.
Subscribe to see which companies asked this question.
class Solution {
public:
bool isValid(string s) {
char stack[5000];
int top = 0;
int len = s.size();
for(int i = 0 ; i < len;i++ ){
if(!top){
stack[top++] = s[i];
}
else{
switch(s[i]){
case '(':
case '[':
case '{':stack[top++] = s[i];break;
case ')':
if(stack[top-1] == '('){
top--;
}
else{
return false;
}
break;
case ']':
if(stack[top-1] == '['){
top--;
}
else{
return false;
}
break;
case '}':
if(stack[top-1] == '{'){
top--;
}
else{
return false;
}
break;
default:break;
}
}
}
if(top == 0){
return true;
}
return false;
}
};