C语言实现检查括号匹配

从头到尾扫描字符串,对不同种类的括号,遇到开括号就入栈,遇到闭括号则检查是否与栈顶开括号类型相同,相同则出栈,否则报错括号不匹配。

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

// 在start与end中搜索匹配 
int fun(char *str, int start, int end)
{
    char chLeft;        // 左括号
    char chRight;       // 右括号
    while ((start <= end) && (str[start] != '\0'))
    {
        switch (str[start])
        {
        case '(':
            chLeft = str[start];
            chRight = ')';
            break;
        case '[':
            chLeft = str[start];
            chRight = ']';
            break;
        case '{':
            chLeft = str[start];
            chRight = '}';
            break;

        case ')':
        case ']':
        case '}':
            return 0;
        default:
            chLeft = '\0';
            break;
        }
        if (str[start] == chLeft)
        {
            int a = 1;
            int b = 0;
            int t = start + 1;
            while ((t <= end) && (str[t] != '\0')) // 搜索匹配的右括号 
            {
                if (str[t] == chLeft)
                    ++a;
                if (str[t] == chRight)
                    ++b;
                if (b>a)
                    return 0;
                if (a == b)      // 再对匹配括号里面的括号进行匹配 
                {
                    if (0 == fun(str, start + 1, t - 1)) // 递归调用 
                        return 0;
                    start = t;
                    break;
                }
                ++t;
            }
            if (a>b)
                return 0;
        }
        ++start;
    }
    return 1;
}

int main(void) {
    char str[1024];
    gets_s(str);
    int length = strlen(str);
    int i = fun(str, 0, length - 1);
    if (i == 1) {
        printf("括号匹配!\n");
    }
    else {
        printf("括号不匹配!\n");
    }
    return 0;
}
  • 9
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值