小括号匹配

任意给定一个字符串,字符串中包含除了空白符、换行符之外的任意字符。你的任务是检测字符串中的圆括号是否配对,即“(”与“)”是否配对。如字符串“((a+b)* (c+d))”中是配对的,而“((a+b)*) c+d))”则不配对。

输入格式:

一个长度不超过100的非空字符串,该字符串中不会出现空格、换行符。

输出格式:

匹配及不匹配见样例。

#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(str);
    int length = strlen(str);
    int i = fun(str, 0, length-1);
    if(i == 1){
        printf("parentheses match!\n");
    }else{
        printf("parentheses do not match!\n");
    }
    return 0;
}

或者这样应该也ok

#include<stdio.h>
int main()
{
		int i=0;
		int m=0,n=0;              
		int judge=0;
	char a[100];
	scanf("%s",a);

	while(a[i]!=0)
	{
		if(a[i]=='(')
		{
		m++;	
		}
		if(a[i]==')')
		{
			n++;
		}
		if(m<n)
	{
			judge++;
		}
		i++;                      //不可以忘记i++啊你......不会用while循环了还是咋地
	}
		if(judge>0)
				{
					printf("parentheses do not match!");
				}
				else
				printf("parentheses match!");	
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值