数据结构:栈和队列的练习题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;
}
相关推荐
散11211 小时前
01数据结构-01背包问题
数据结构
消失的旧时光-194311 小时前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww11 小时前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚13 小时前
[数据结构] 排序
数据结构
睡不醒的kun15 小时前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌15 小时前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long16 小时前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn16 小时前
Redis7底层数据结构解析
前端·数据结构·bootstrap
我星期八休息16 小时前
深入理解跳表(Skip List):原理、实现与应用
开发语言·数据结构·人工智能·python·算法·list
和编程干到底17 小时前
数据结构 栈和队列、树
数据结构·算法