C语言-括号匹配的检验
使用下面代码前,需要引入基本算法。另外数据结构的基本算法已经更新,新增了“队列”的基本算法。
基本算法地址:https://www.orbpi.cn/article/shujujiegoujibensuanfaluru.html
问题描述
假设表达式中允许有两种括号:圆括号和方括号,其嵌套的顺序随意,即(()[ ])或[([ ] [ ])]等为正确格式,[( ])或(((]均为不正确的格式。检验括号是否匹配的方法可用“期待的紧迫程度”这个概念来描述。例如:考虑下列的括号序列: [ ( [ ] [ ] ) ]
1 2 3 4 5 6 7 8
基本要求:
读入含有圆括号和方括号的任意序列,输出“匹配”或“此串括号匹配不合法”。
实现代码
/*
**实验题二
**括号匹配的检验
**ASORB&201810
*/
#include"DataH.h"
int _pei(char c){
//返回匹配值
switch (c){
case '[':return 1;
case ']':return 2;
case '(':return 3;
case ')':return 4;
}
}
int main(){
char c;
SElemType e;
SqStack S;
InitStack(&S); //初始化
while ((c = getchar()) != '\n'){
if (c == '(' || c == '[')
Push(&S, _pei(c));
else if (c == ')'||c == ']'){
if (Pop(&S, &e)){
if (e + 1 != _pei(c)) {
c = NULL;
break;
}
}
else{
c = NULL;
break;
}
}
}
if (!StackEmpty(S))c = NULL;
if (c)
printf("匹配!\n");
else
printf("此串括号不匹配!\n");
DestroyStack(&S); //销毁
fflush(stdin); //防闪
getchar();
return 0;
}
效果图

END
文章仅代表作者个人观点,转载请注明出处!
文章地址:https://www.orbpi.cn/article/cyuyanguahaopipeidejianyan.html

浙公网安备 33010602011771号