括号匹配
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
1.有效字符串需满足: 左括号必须用相同类型的右括号闭合。
2. 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例1:
输入: "()"
输出: true
示例2:
输入: "()[]{}"
输出: true
示例3:
输入: "(]"
输出: false
示例4:
输入: "([)]"
输出: false
typedef int type;
typedef struct Stack {
type* array;
size_t size;
size_t capacity;
}Stack;
//栈初始化
void StackInit(Stack* sl, size_t n) {
sl->array = (type*)malloc(sizeof(type) * n);
sl->capacity = n;
sl->size = 0;
}
//入栈
void StackPush(Stack* sl, type x) {
if (sl->size == sl->capacity) {
sl->capacity *= 2;
sl->array = (type*)realloc(sl->array, sl->capacity);
//扩容
}
//尾插
sl->array[sl->size++] = x;
}
//出栈
void StackPop(Stack* sl) {
if (sl->size) {
sl->size--;
}
}
//获取栈顶元素
type StackTop(Stack* sl) {
return sl->array[sl->size - 1];
}
//栈判空
int StackEmpty(Stack* sl) {
if (sl->size == 0) {
return 1;
}
return 0;
}
//获取栈长度
size_t StackSize(Stack* sl) {
return sl->size;
}
//栈销毁
void StackDestory(Stack* sl) {
free(sl->array);
sl->array = NULL;
sl->size = 0;
sl->capacity = 0;
}
bool isValid(char* s) {
Stack st;
StackInit(&st);
//左右括号的映射
static char map[][2] = { {'(',')'},{'[',']'},{'{','}'} };
//遍历字符串,左括号全部入栈
while (*s) {
int i = 0;
//判断是否为左括号
for (; i < 3; ++i) {
if (*s == map[i][0]) {
//左括号入栈
StackPush(&st, *s);
++s;
}
}
//上边循环走完出来就代表不是左括号
if (i == 3) {
//防止栈为空
if (StackEmpty(&st)) {
return false;
}
//用栈顶元素跟这个右括号匹配
char top = StackTop(&st);
for (int j = 0; j < 3; j++) {
if (*s == map[j][1]) {
if (map[j][1] == top) {
//左右括号匹配,出栈
StackPop(&st);
++s;
break;
}
else {
return false;
}
}
}
}
}
if (StackEmpty(&st)) {
return true;
}
return false;
}