0
点赞
收藏
分享

微信扫一扫

Flink分区相关

仲秋花似锦 2024-03-04 阅读 16

点击查看题目

在这里插入图片描述

在这里插入图片描述

思路:

在这里插入图片描述
在这里插入图片描述

实现栈在上个博客中已经写过,在这就不在赘述
点击进入博客:【数据结构】实现栈

#include<stdio.h>
#include<assert.h>
#include<stdbool.h>

typedef int STDataType;

typedef struct Stack
{
	STDataType* a;
	int top;
	int capacity;
}ST;

//初始化
void STInit(ST* pst)
{
	assert(pst);

	pst->a = NULL;
	pst->capacity = 0;
	pst->top = 0;//指向栈顶元素的下一个
}

//销毁
void STDestroy(ST* pst)
{
	assert(pst);

	if (pst->a != NULL)
	{
		free(pst->a);
		pst->a = NULL;
		pst->capacity = 0;
		pst->top = 0;
	}
}

//栈顶插入
void STPush(ST* pst, STDataType x)
{
	assert(pst);

	//判断是否需要增容
	if (pst->top == pst->capacity)
	{
		int newcapacity = (pst->capacity == 0) ? 4 : 2 * pst->capacity;
		ST* tmp = (ST*)realloc(pst->a, newcapacity * sizeof(ST));
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		pst->a = tmp;
		pst->capacity = newcapacity;
	}

	//插入数据
	pst->a[pst->top] = x;
	pst->top++;
}

//栈顶删除
void STPop(ST* pst)
{
	assert(pst);
	assert(pst->top > 0);

	pst->top--;
}

//显示栈顶元素
STDataType STTop(ST* pst)
{
	assert(pst);
	assert(pst->top > 0);

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

//是否为空
bool STEmpty(ST* pst)
{
	assert(pst);

	return pst->top == 0;
}

//大小
int STSize(ST* pst)
{
	assert(pst);

	return pst->top;
}

上面是实现栈的代码,下面写本题代码

bool isValid(char* s) {
    ST st;
    STInit(&st);
    while(*s)
    {
        //插入栈
        if(*s=='{'||*s=='('||*s=='[')
        {
            STPush(&st,*s);
        }
        else
        {
            if(STEmpty(&st))
            {
                return false;
            }
            if((*s==')'&&STTop(&st)!='(')
            ||(*s=='}'&&STTop(&st)!='{')
            ||(*s==']'&&STTop(&st)!='['))
            {
                return false;
            }
            STPop(&st);
        }
        s++;
    }
    if(!STEmpty(&st))
    {
        return false;
    }
    STDestroy(&st);
    return true;
}

你觉得上面的代码有问题吗?如果觉得没有的话,请往上看我们注意的第二条:要将栈销毁。在上面这段代码中只有返回true时才销毁了栈,返回false时都没有销毁。所以让我们修改一下

bool isValid(char* s) {
    ST st;
    STInit(&st);
    while(*s)
    {
        if(*s=='{'||*s=='('||*s=='[')
        {
            STPush(&st,*s);
        }
        else
        {
            if(STEmpty(&st))
            {
                STDestroy(&st);
                return false;
            }
            if((*s==')'&&STTop(&st)!='(')
            ||(*s=='}'&&STTop(&st)!='{')
            ||(*s==']'&&STTop(&st)!='['))
            {
                STDestroy(&st);
                return false;
            }
            STPop(&st);
        }
        s++;
    }
    if(!STEmpty(&st))
    {
        STDestroy(&st);
        return false;
    }
    STDestroy(&st);
    return true;
}

其实最后判断是否为空,不为空返回false,为空返回true也可以写成这样。

    bool ret=STEmpty(&st);
    STDestroy(&st);
    return ret;

好了,那么本篇博客就到此结束了,如果你觉得本篇博客对你有些帮助,可以给个大大的赞👍吗,感谢看到这里,我们下篇博客见❤️

举报

相关推荐

0 条评论