解题思路:
1.利用栈先进先出的特点,遇到左括号就使其进栈,遇到右括号就弹出栈顶元素与右括号进行匹配,匹配成功则进行接着进行匹配。
2.有效字符串长度必然是偶数。
3.最后栈中如果依然存在元素则结果为false,例如"{[()]",最后栈中会留下'{',故匹配失败。
4.特殊情况:字符串长度为1,例如'('或者']'就需要进行特殊的处理。
C语言解题代码如下:
typedef char STDatatype; typedef struct Stack { STDatatype* a; int top; int capacity; }Stack; void StackInit(Stack* ps); void StackDestroy(Stack* ps); void StackPush(Stack* ps,STDatatype x); void StackPop(Stack* ps); int StackSize(Stack* ps); bool StackEmpty(Stack* ps); STDatatype StackTop(Stack* ps); void StackInit(Stack* ps) { assert(ps); ps->a = (STDatatype*)malloc(sizeof(STDatatype) * 4); if (ps->a == NULL) { perror("malloc fail"); return; } ps->capacity = 4; ps->top = 0; } void StackPush(Stack* ps, STDatatype x) { assert(ps); //检查是否需要扩容 if (ps->capacity == ps->top) { STDatatype* tmp = (STDatatype*)realloc(ps->a, sizeof(STDatatype) * ps->capacity * 2); if (tmp == NULL) { perror("realloc fail"); return; } ps->a = tmp; ps->capacity *= 2; } ps->a[ps->top] = x; ps->top++; } void StackPop(Stack* ps) { assert(ps); assert(!StackEmpty(ps)); ps->top--; } int StackSize(Stack* ps) { assert(ps); return ps->top; } bool StackEmpty(Stack* ps) { assert(ps); return ps->top == 0; } void StackDestroy(Stack* ps) { assert(ps); free(ps->a); ps->a == NULL; ps->capacity = 0; ps->top = 0; } STDatatype StackTop(Stack* ps) { assert(ps); assert(!StackEmpty(ps)); return ps->a[ps->top - 1]; } bool isValid(char * s){ Stack st; StackInit(&st); while(*s) { if(*s == '('||*s == '['||*s=='{') { StackPush(&st,*s); } else { if(StackEmpty(&st)) { StackDestroy(&st); return false; } STDatatype tmp = StackTop(&st); StackPop(&st); if(tmp != '(' && *s == ')' ||tmp != '[' && *s == ']' ||tmp != '{' && *s == '}') { StackDestroy(&st); return false; } } s++; } bool ret = StackEmpty(&st); StackDestroy(&st); return ret; }