【有效的括号】

题目

1、左括号入栈
2、右括号出栈顶括号进行匹配

typedef char STDataType;
//元素为char类型
typedef struct Stack
{
	STDataType* a;
	//动态的开辟空间
	int top;
	int capacity;
}ST;

void StackInit(ST* ps)//初始化
{
	assert(ps);

	ps->a = (STDataType*)malloc(sizeof(STDataType) * 4);
	if (ps->a == NULL)
	{
		printf("malloc fail\n");
		exit(-1);
	}

	ps->capacity = 4;
	ps->top = 0;//top一开始指向0位置(也可以指向-1位置)
}

void StackDestory(ST* ps)//销毁
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	
	ps->top = ps->capacity = 0;
}

int StackSize(ST* ps)//元素个数
{
	assert(ps);

	return ps->top;//top从0开始
}

void StackPush(ST* ps, STDataType x)//入栈
{
	assert(ps);

	//空间不够用 开辟空间
	if (ps->top == ps->capacity)
	{
		STDataType* tmp = (STDataType*)realloc(ps->a, ps->capacity * 2 * sizeof(STDataType));
		if (tmp == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}
		else
		{
			ps->a = tmp;
			ps->capacity *= 2;
		}
	}

	ps->a[ps->top] = x;
	ps->top++;
}

void StackPop(ST* ps)//出栈
{
	assert(ps);
	
	assert(ps->top > 0);

	ps->top--;
}

STDataType StackTop(ST* ps)//取栈顶元素
{
	assert(ps);

	assert(ps->top > 0);

	return ps->a[ps->top - 1];
}

bool StackEmpty(ST* ps)//判断是否为空
{
	assert(ps);

	return ps->top == 0;
}

题目求解

bool isValid(char * s){
    ST st;
    StackInit(&st);
    //字符串没有走到结束条件
    while((*s)!='\0')
    {
        if((*s) == '('||(*s) == '['||(*s) == '{')
        {
            StackPush(&st,*s);
        }
        else
        {
            if(StackEmpty(&st)){
                StackDestory(&st);//内存泄漏
                return false;
            }
            char top = StackTop(&st);
            StackPop(&st);
            if((*s == ')'&&top !='(')||
            (*s == ']'&&top !='[')||
            (*s == '}'&&top !='{'))
            {
                StackDestory(&st);
                return false;
            }
        }
        s++;
    }

    bool ret = StackEmpty(&st);
    StackDestory(&st);
    return ret;
}

你可能感兴趣的:(#,数据结构(初),运维,数据结构)