有效的括号 题目链接
// 栈结构
typedef char valuetype;
typedef struct {
valuetype* arr;
int top;
int capacity;
} Stack;
void Init(Stack* stack);
void Push(Stack* stack, valuetype value);
void Pop(Stack* stack);
valuetype Top(Stack* stack);
int Size(Stack* stack);
bool Empty(Stack* stack);
void Destroy(Stack* stack);
bool isValid(char* s) {
Stack stack;
Init(&stack);
while (*s) {
if (*s == '(' || *s == '[' || *s == '{') {
Push(&stack, *s); // 1.左括号入栈;
}
else { // 2.比较。
if (Empty(&stack)) { // 2.1右括号比左括号多
Destroy(&stack);
return false;
}
else { // 2.2 比较左括号与右括号是否匹配
char ch = Top(&stack);
Pop(&stack);
if ((ch == '(' && *s != ')') ||
(ch == '[' && *s != ']') ||
(ch == '{' && *s != '}')) {
Destroy(&stack);
return false;
}
}
}
s++;
}
// 如果栈里还剩有括号,说明左右括号没有对应
bool res = Empty(&stack);
Destroy(&stack);
return res;
}
void Init(Stack* stack) {
assert(stack);
stack->arr = NULL;
stack->capacity = stack->top = 0;
}
void Push(Stack* stack, valuetype value) {
assert(stack);
if (stack->top == stack->capacity) {
stack->capacity = stack->capacity == 0 ? 10 : (int)(stack->capacity * 1.5);
stack->arr = (valuetype*)realloc(stack->arr, sizeof(valuetype) * stack->capacity);
if (stack->arr == NULL) {
perror("realloc failed in the function Push(Stack*, valuetype).");
return;
}
}
stack->arr[stack->top++] = value;
}
void Pop(Stack* stack) {
assert(stack && stack->top > 0);
stack->top--;
}
valuetype Top(Stack* stack) {
assert(stack && stack->top > 0);
return stack->arr[stack->top - 1];
}
int Size(Stack* stack) {
assert(stack);
return stack->top;
}
bool Empty(Stack* stack) {
assert(stack);
return stack->top == 0;
}
void Destroy(Stack* stack) {
assert(stack);
free(stack->arr);
stack->arr = NULL;
stack->capacity = stack->top = 0;
}