這里,我提供一種用棧來解決的方法:
思路:棧的結構是先進后出,這樣我們就可以模擬棧結構了,如果是‘(’、‘{’、‘[’任何一種,直接push進棧就可以了,如果是‘}’、‘)’、‘]’任何一種就開始判斷,看棧pop的是否和對應的字符匹配。
?文章來源地址http://www.zghlxwxcb.cn/news/detail-677329.html
?下面是源碼:
typedef char STDateType;
typedef struct Stack
{
STDateType* a;
int top;
int capacity;
}Stack;
void StackInit(Stack* ps);
void StackPush(Stack* ps, STDateType x);
void StackPop(Stack* ps);
STDateType StackTop(Stack* ps);
int StackSize(Stack* ps);
bool StackEmpty(Stack* ps);
void StackDestroy(Stack* ps);
void StackInit(Stack* ps)
{
assert(ps);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
void StackPush(Stack* ps, STDateType x)
{
assert(ps);
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDateType* tmp = (STDateType*)realloc(ps->a, sizeof(STDateType) * newcapacity);
if (tmp == NULL)
{
perror("realloc fail");
exit(-1);
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
void StackPop(Stack* ps)
{
assert(ps);
--ps->top;
}
STDateType StackTop(Stack* ps)
{
assert(ps);
return ps->a[ps->top - 1];
}
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->top = ps->capacity = 0;
}
bool isValid(char * s){
Stack st;
StackInit(&st);
char top;
while(*s)
{
if((*s == '(') || (*s == '[') || (*s == '{'))
{
StackPush(&st,*s);
}else
{
if(StackEmpty(&st))
{
StackDestroy(&st);
return false;
}
top = StackTop(&st);
StackPop(&st);
if((*s == ']' && top != '[')
|| (*s == '}' && top != '{')
|| (*s == ')' && top != '('))
{
StackPop(&st);
StackDestroy(&st);
return false;
}
}
++s;
}
bool ret = StackEmpty(&st);
StackDestroy(&st);
return ret;
}
?文章來源:http://www.zghlxwxcb.cn/news/detail-677329.html
?
?
?
到了這里,關于LeetCode——有效的括號的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!