数据结构:栈和队列的练习题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;
}
相关推荐
wuyk55524 分钟前
1.栈:后进先出的线性数据结构
c语言·数据结构·stm32·单片机
LuminousCPP1 小时前
数据结构-时间与复杂度|时间/空间复杂度 + 两道力扣练习 + 二分查找复盘
c语言·数据结构·经验分享·算法·leetcode
Nil2081 小时前
leetcode 三数之和
数据结构·算法·leetcode
青山木2 小时前
Hot 100 --- 最小栈
java·数据结构·算法·leetcode
疯狂打码的少年2 小时前
【数据结构】栈的应用:表达式求值(后缀表达式)
java·数据结构·笔记·算法
SunnyByte3 小时前
排序进阶:快速排序与归并排序的迭代实现,并与递归版本对比
c语言·数据结构·算法·排序算法
wabs6663 小时前
关于图论【最短路径之Bellman_ford 算法(判断负权回路)|卡码网95.城市间货物运输II的思考】
数据结构·算法·图论·bellman_ford算法·卡码网·判断负权回路
wabs6665 小时前
关于哈希表【力扣15.三数之和的思考】
数据结构·算法·leetcode·散列表·哈希表·三数之和
疯狂打码的少年6 小时前
【数据结构】队列的应用:循环队列
数据结构·笔记·算法
Doraemomo15 小时前
数据结构-环形链表
java·数据结构·链表