7-1 Balancing Symbols

Balancing symbols: Check if parenthesis (), brackets[], and braces{} are balanced.

输入格式:

1 line
An expression includes variables and symbols. The max length is 50.

输出格式:

1 line
If all the () [] {} are balanced, then output 0.
If () are not balanced, output 1; If [] not balanced, output 2; If {} not balance, output 3.
If more than one symbol are not balanced, output corresponding numbers, sort them in ascending order and divided them by comma.

输入样例:

在这里给出一组输入。例如:

{a*(b-c)-x/2]

输出样例:

在这里给出相应的输出。例如:

2,3,

 C语言代码

简要分析:

只需要检测括号数量是否匹配,不需要检测格式,故仅需计算括号数量即可。

代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

main(){
    char string[50];
    fgets(string,50,stdin);
    int i;
    int result[3]={0,0,0};
    for(i=0;i<strlen(string);i++){
        if(string[i]=='(') result[0]++;
        if(string[i]==')') result[0]--;
        if(string[i]=='[') result[1]++;
        if(string[i]==']') result[1]--;
        if(string[i]=='{') result[2]++;
        if(string[i]=='}') result[2]--;
    }
    int flag=0;
    for(i=0;i<3;i++){
        if(result[i]){
            printf("%d,",i+1);
            flag=1;
        }
    }
    if(!flag) printf("0");
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值