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;
}
本文介绍了一个简单的算法,用于检查字符串中的括号是否正确配对。该算法使用了栈的概念来确保括号的顺序正确,例如'()'和'()[]{}
929

被折叠的 条评论
为什么被折叠?



