给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
来源:LeetCode
#include <stdio.h>
#include <string.h>
typedef enum {
true = 1,
false = 0,
} bool;
enum {
ONE = 1,
SMALL_1 = '(',
SMALL_2 = ')',
TWO = 2,
MIDDLE_1 = '[',
MIDDLE_2 = ']',
BIG_1 = '{',
BIG_2 = '}'
};
bool isValid(char *s)
{
if (!s) {
return false;
}
int len = strlen(s);
int total = 0;
int *arr = (int *)malloc(sizeof(int) * len);
for (int i = 0; i < len; ++i) {
if (s[i] == SMALL_1 || s[i] == MIDDLE_1 || s[i] == BIG_1) {
arr[total] = s[i];
total++;
} else if (s[i] == SMALL_2 || s[i] == MIDDLE_2 || s[i] == BIG_2) {
--total;
if (total < 0 || ((s[i] - arr[total] != ONE) && (s[i] - arr[total] != TWO))) {
return false;
}
} else {
return false;
}
}
free(arr);
return total == 0;
}
int main()
{
char str[] = "{}[]()";
bool res = isValid(str);
return res;
}