1、括号的匹配(表达式的合法性检查)[问题描述]假设一个表达式有英文字母(小写)、运算符(+,—,*,/)和左右小(圆)括号构成,以“@”作为表达式的结束符
请编写一个程序检查表达式中的左右圆括号是否匹配,若匹配,则返回“YES”;否则返回“NO”
假设表达式长度小于255,左圆括号少于20个
[问题分析]假设输入的字符串存储在c中(varc:string[255])
我们可以定义一个栈:vars:array[1
maxn]ofchar;top:integer;用它来存放表达式中从左往右的左圆括号(maxn=20)
算法的思路为:顺序(从左往右)扫描表达式的每个字符c[i],若是“(”,则让它进栈;若遇到的是“)”,则让栈顶元素出栈;当栈发生下溢或当表达式处理完毕而栈非空时,都表示不匹配,返回“NO”;否则表示匹配,返回“YES”
[参考程序]programlx5;constmaxn=20;varc:string;functionjudge(c:string):boolean;vars:array[1
maxn]ofchar;top,i:integer;ch:char;beginjudge:=true;top:=0;i:=1;ch:=c[i];whilech'@'dobeginif(ch='(')or(ch=')')thencasechof'(':begintop:=top+1;s[top]:='('end;')':iftop>0thentop:=top-1elsebeginjudge:=false;exitend;end;i:=i+1;ch:=c[i];end;iftop0thenjudge:=false;end;begin{main}assign(