uva673 栈 括号匹配

本文介绍了一种使用栈解决括号匹配问题的方法。通过定义特殊字符串来检查输入字符串中的小括号和中括号是否正确配对。文章提供了一个简单的C语言实现案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

673 - Parentheses Balance括号匹配

输入一些由小括号和中括号组成的字符串,判断字符串是否正确。

栈的基本应用,水题。自己比较得意的是如何判断是否匹配。方法是:
little = ‘(’ + ‘)’;
middle = ‘[’ + ‘]’;
判断当前字符和栈顶字符相加是否等于little 或middle

代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const int little = '(' + ')';
const int middle = '[' + ']';

void judge(char c, char *parenthess, int *top)
{
    if (c == ')' || c == ']')
    {
        if (c + parenthess[*top - 1] == little || c + parenthess[*top - 1] == middle)
        {
            --*top;
            return;
        }
    }
    parenthess[(*top)++] = c;
}

int main()
{
    int n, top;
    char parentheses[200];
    char c;

    while (~scanf("%d", &n))
    {
        getchar();
        while (n--)
        {
            parentheses[0] = '#';
            top = 1;

            c = getchar();
            while (c != '\n')
            {
                judge(c, parentheses, &top);
                c = getchar();
            }

            if (top == 1)
            {
                printf("Yes\n");
            }
            else
            {
                printf("No\n");
            }
        }
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值