白居易秋夜赏析:括号匹配问题(pascal)

来源:百度文库 编辑:杭州交通信息网 时间:2024/04/29 22:06:09
判断包含有括号{,[,<,(,),>,],}的字符串是否匹配。
样例1:
输入:abc{a[bb]m}aa<ss>
输出:yes
样例2:
输入:abc{a[bb]maa<ss>
输出:no

用pascal ,,给出原程序 谢谢~!

const
op1='{[<(';
op2='}]>)';
var
s:array[1..1000] of char;
top,p1,p2,l,i:longint;
st:string;
ch:char;bj:boolean;
begin
readln(st);
top:=0;l:=length(st);
bj:=true;
for i:=1 to l do begin
ch:=st[i];
if pos(ch,op1)<>0 then begin
inc(top);s[top]:=ch;
end
else if pos(ch,op2)<>0 then begin
if top=0 then begin bj:=false;break;end
else begin
p2:=pos(ch,op2);
ch:=s[top];
p1:=pos(ch,op1);
if p1=p2 then dec(top)
else begin bj:=false;break;end;
end;
end;
end;
if top=0 and bj then writeln('yes')
else writeln('no');
end.

var str,zhan:string;
i,n,zi:integer;
begin
read(str);
n:=length(str);
zi:=1;
for i:=1 to n do
begin
if (str[i]='<') or (str[i]='(') or (str[i]='{') or (str[i]='[') then
begin
zhan[zi]:=str[i];
inc(zi);
end;
case str[i] of
'>':if (zi-1>0)and(zhan[zi-1]='<') then dec(zi)
else begin writeln('no');halt;end;
')':if (zi-1>0)and(zhan[zi-1]='(') then dec(zi)
else begin writeln('no');halt;end;
'}':if (zi-1>0)and(zhan[zi-1]='{') then dec(zi)
else begin writeln('no');halt;end;
']':if (zi-1>0)and(zhan[zi-1]='[') then dec(zi)
else begin writeln('no');halt;end;
end;
end;
if zi=1 then
writeln('yes')
else writeln('no');

end.

这题应该用eof