括号匹配()

回学校补作业哩,悲。

国庆假期爸妈是一点时间不留给我写作业啊

假设一个算术表达式中包含圆括号、方括号两种类型的括号,试编写一个判断表达式中括号是否匹配的程序,匹配返回Match succeed!,否则返回Match false!。

[1+2*(3+4*(5+6))]括号匹配

(1+2)*(1+2*[(1+2)+3)括号不匹配

输入

包含圆括号、方括号两种类型括号的算术表达式

输出

匹配输出Match succeed!

不匹配输出 Match false!

输入[1+2* (3+4*(5+6))]

输出Match succeed!

测试输入期待的输出时间限制内存限制额外进程
测试用例 1以文本方式显示
  1. [1+2*(3+4*(5+6))]↵
以文本方式显示
  1. Match succeed!↵
1秒64M0
测试用例 2以文本方式显示
  1. (1+2)*(1+2*[(1+2)+3)↵
以文本方式显示
  1. Match false!↵
1秒64M0

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100

int top = -1;
char stack[MAX_SIZE];
void push(char c)
{
    if (top == MAX_SIZE - 1)
    {
        printf("Stack Overflow\n");
        return;
    }
    stack[++top] = c;
}
char pop()
{
    if (top == -1)
    {
        printf("Stack Underflow\n");
        return '\0';
    }
    return stack[top--];
}
int Match(char *Formula)
{
    for (int i = 0; i < strlen(Formula); i++)
    {
        if (Formula[i] == '(' || Formula[i] == '[')
            push(Formula[i]);
        else if (Formula[i] == ')')
        {
            if (top != -1 && stack[top] == '(')
                pop();
            else
                return 0;
        }
        else if (Formula[i] == ']')
        {
            if (top != -1 && stack[top] == '[')
                pop();
            else
                return 0;
        }
    }
    return top == -1;
}

int main()
{
    char Formula[MAX_SIZE];
    fgets(Formula, MAX_SIZE, stdin);
    if (Match(Formula))
        printf("Match succeed!\n");
    else
        printf("Match false!\n");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值