LeetCode——有效的括号

LeetCode——有效的括号_第1张图片

这里,我提供一种用栈来解决的方法:

思路:栈的结构是先进后出,这样我们就可以模拟栈结构了,如果是‘(’、‘{’、‘[’任何一种,直接push进栈就可以了,如果是‘}’、‘)’、‘]’任何一种就开始判断,看栈pop的是否和对应的字符匹配。

 

LeetCode——有效的括号_第2张图片

LeetCode——有效的括号_第3张图片 

 下面是源码:

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;
}   

 

 

你可能感兴趣的:(LeetCode,leetcode,算法,c语言,c++,数据结构)