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");
}