给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串 s
,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
- 每个右括号都有一个对应的相同类型的左括号。
示例 1:
输入:s = "()" 输出:true
示例 2:
输入:s = "()[]{}" 输出:true
示例 3:
输入:s = "(]" 输出:false
提示:
1 <= s.length <= 104
s
仅由括号'()[]{}'
组成-
typedef char STDatatype; struct stack { STDatatype* arr; int top; int capacity; }; typedef struct stack ST; void STInit(ST* ps);//初始化 void STDestory(ST* ps);//销毁 void STPush(ST* ps, STDatatype x);//压栈 void STPop(ST* ps);//出栈; STDatatype STTop(ST* ps);//栈顶的数 int STSize(ST* ps);//栈的大小 bool STEmpty(ST* ps); void STInit(ST* ps) { assert(ps); ps->arr = NULL; ps->top = 0; ps->capacity = 0; } void STDestory(ST* ps) { assert(ps); free(ps->arr); ps->arr = NULL; ps->top = 0; ps->capacity = 0; } void STPush(ST* ps, STDatatype x) { assert(ps); //满了扩容 if (ps->top == ps->capacity) { int newcapacity; if (ps->capacity == 0) { newcapacity = 4; } else { newcapacity = 2 * ps->capacity; } STDatatype* temp = (STDatatype*)realloc(ps->arr, newcapacity * sizeof(STDatatype)); if (temp == NULL) { perror("realloc fail!"); return; } ps->arr = temp; ps->capacity = newcapacity; } ps->arr[ps->top] = x; ps->top++; } void STPop(ST* ps) { assert(ps); ps->top--; } STDatatype STTop(ST* ps) { assert(ps); assert(!STEmpty(ps)); return ps->arr[ps->top - 1]; } int STSize(ST* ps) { assert(ps); return ps->top; } bool STEmpty(ST* ps) { assert(ps); return ps->top == 0; } bool isValid(char* s) { ST st; STInit(&st); while(*s) { if(*s=='(' || *s=='[' || *s=='{') { STPush(&st,*s); } else { if(STEmpty(&st)) { return false; } char top=STTop(&st); STPop(&st); if((*s==')' && top!='(') ||(*s==']' && top!='[') ||(*s=='}' && top!='{') ) { return false; } } s++; } bool ret=STEmpty(&st); STDestory(&st); return ret; }