括号匹配问题

来源:互联网 发布:易语言外网聊天室源码 编辑:程序博客网 时间:2024/05/17 01:23

    假设表达式中包含三种括号:圆括号、方括号和花括号,它们可以相互嵌套,如({ }[ ]([{ }]))等均为正确的格式,而{]}等为不正确的格式。以下为算法程序:

/*括号匹配问题*/#include <stdio.h>#include <stdlib.h>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");elseprintf("匹配失败!\n");system("pause");return 0;}


0 0