数据结构:栈和队列的练习题1(括号匹配问题)

题目描述:


思路:我们首先可以把出现的情况大致分为以下几类:


因为涉及匹配问题,所以所有的左括号和右括号肯定要分开来整理。如果我们直接去匹配的话(像第一行的从左到右独立匹配)是行得通的,但是遇到第二行的情况就识别不了了,因为第二种有顺序要求,先识别的左括号必须和后识别的右括号配对,这与栈的性质十分相似,所以我们想到用栈来实现这道题:

二者联系方式:

当遇到左括号时便使其进入栈,当遇到右括号时再去栈顶元素和右括号进行匹配。如果是同种类型的括号就匹配成功,将栈顶元素出栈并继续匹配;若匹配失败则直接return。

为预防碰到括号数量不对等时,我们可以引入count变量来记录左括号和右括号的个数,一次来解决做题时遇到的一些问题。

完整代码如下:

cpp 复制代码
typedef char DataType;

typedef struct Stack
{
    DataType* p;
    int top;
    int Capacity;
}ST;

// 初始化函数
void STInit(ST* pst)
{
    assert(pst);
    pst->p = NULL;
    pst->Capacity = 0;
    pst->top = 0;
}


// 入栈  出栈
void STPush(ST* pst, DataType x)
{
    assert(pst);
    //扩容
    if (pst->Capacity == pst->top)  
    {
        int NewCapacity = pst->Capacity == 0 ? 4 : 2 * pst->Capacity;
        DataType* tmp = (DataType*)realloc(pst->p, sizeof(DataType) * NewCapacity);

        pst->Capacity = NewCapacity;
        pst->p = tmp;
    }

    pst->p[pst->top] = x;
    pst->top++;
}

//出栈
void STPop(ST* pst)
{
    assert(pst);
    pst->top--;
}

// 取栈顶数据
DataType STTop(ST* pst)
{
    return pst->p[pst->top - 1];
}

// 判空
bool STEmpty(ST* pst)
{
    if (pst->top == 0)
    {
        return false;
    }
    else
    {
        return true;
    }
}

// 获取数据个数
int STSize(ST* pst)
{
    return pst->top;
}



bool isValid(const char* s)
{
    ST st;
    STInit(&st);

    int count=0;
    int count1 = 0;
    int count2 = 0;

    while (*s != '\0')
    {
        if (*s == '(' || *s == '[' || *s == '{')
        {
            STPush(&st, *s);
            count++;
            count1++;
        }
        if (*s == ')' || *s == ']' || *s == '}')
        {
            count--;
            count2++;
            //没有左括号的情况
            if (STEmpty(&st) == false)
            {
                return false;
            }


            char ret = STTop(&st);
            //匹配成功
            if ((*s == ')' && ret == '(') || (*s == ']' && ret == '[') || (*s == '}' && ret == '{'))
            {
                STPop(&st);
            }
            else
            {
                //匹配失败
                return false;
            }
        }
        s++;
    }

    if (count%2!=0||count1!=count2)
    {
        return false;
    }

    return true;
}
相关推荐
fish_zzzz5 小时前
笔记-论数据结构1
数据结构
傅科摆 _ py8 小时前
链表力扣复习
数据结构·leetcode·链表
inrichtt9 小时前
第十一课时:串口中断接收与回调函数实战解析
c语言·数据结构·stm32·单片机·嵌入式硬件
信奥卷王10 小时前
[GESP202406 六级] 二叉树(含视频)
数据结构·算法
starzy199011 小时前
KafkaProducer 源码深度剖析:支撑高吞吐的数据结构设计
大数据·数据结构·kafka
罗湖老棍子1 天前
【例 1】Sightseeing Trip(信息学奥赛一本通- P1494)(洛谷-P10927)
数据结构·算法·图论·最短路·floyd·最小环
郝亚军1 天前
manifest 中 `sha256` 与 `signValue` 的作用
java·开发语言·数据结构
Nil2081 天前
LeetCode 283移动零
数据结构·算法·leetcode
库玛西1 天前
外部排序全解析:败者树、置换-选择排序与最佳归并树
c语言·数据结构·c++·笔记·考研·算法
花间相见1 天前
【计算基础|MySQL08】索引(上):为什么是 B+ 树
数据结构·mysql·算法·架构