假设表达式中包含三种括号:圆括号、方括号和花括号,它们可以相互嵌套,如({ }[ ]([{ }]))等均为正确的格式,而{]}等为不正确的格式。以下为算法程序:
/*括号匹配问题*/#include#include int main(){ int count[3] = { 0 }; char ch; while ((ch = getchar()) != EOF) { switch (ch) { case '(': count[0]++; break; case '[': count[1]++; break; case '{': count[2]++; break; case ')': if (count[0] == 0) { printf("匹配失败!\n"); system("pause"); return 0; } count[0]--; break; case ']': if (count[1] == 0) { printf("匹配失败!\n"); system("pause"); return 0; } count[1]--; break; case '}': if (count[2] == 0) { printf("匹配失败!\n"); system("pause"); return 0; } count[2]--; break; } } if (count[0] == 0 && count[1] == 0 && count[2] == 0) printf("匹配成功!\n"); else printf("匹配失败!\n"); system("pause"); return 0;}