7-1 实验9_1_括号匹配 (100分)
任意给定一个字符串,字符串中包含除了空格、换行符之外的任意字符。你的任务是检测字符串中的小括号是否配对,即“(”与“)”是否配对。如字符串“((a+b)* (c+d))”中小括号是配对的,而“((a+b)*) c+d))”则不配对。
程序运行效果:
Sample 1: ((a+b)*(c+d)) ↙
parentheses match!↙
Sample 2:
((a+b)*)c+d)) ↙
parentheses do not match!↙
输入格式:
一个长度不超过100的非空字符串,该字符串中不会出现空格、换行符。
输出格式:
见程序运行效果。
输入样例:
((a+b)*(c+d))
输出样例:
parentheses match!
#include<stdio.h>
int main() {
char a[1000];
scanf("%s",a);
char char1='(',char2=')';
int i=0,c=0;
while (a[i]!='\0'){
if (a[i]==char1){
c++;
}
if (a[i]==char2){
c--;
}
if (c<0){
printf("parentheses do not match!");
return 0;
}
i++;
}
if (c>0){
printf("parentheses do not match!");
}
if (c==0){
printf("parentheses match!");
}
return 0;
}