pascal 括号配对问题

问题描述:

pascal 括号配对问题
假设表达式中允许包含两种括号:圆括号和方括号,其嵌套的顺序随意,如(〔 〕())或〔(〔 〕〔 〕)〕等为正确的匹配,〔(〕)或(〔 〕( )或 (()))均为错误的匹配.
现在的问题是,要求检验一个给定表达式中的括弧是否正确匹配?
输入一个只包含圆括号和方括号的字符串,判断字符串中的括号是否匹配,匹配就输出 “OK” ,不匹配就输出“Wrong”.
输入一个字符串:
〔(〔〕〔〕)〕
输出:
OK
var
a:string;
i,j:integer;
now:array[1..40]of char;
l:integer;
ans:integer;
top:integer;
begin
read(a);
l:=length(a);
ans:=0;
top:=0;
if (a[1]=')') or (a[1]=']') then
begin
ans:=1;
write('Wrong');
end;
while (a[i]' ') and (ans1) do
begin
if (a[i]='(') and (a[i]='[') then
begin
top:=top+1;
now[top]:=a[i];
end;
if (a[i]=')') then
if now[top]='(' then
top:=top-1
else
begin
write('wrong');
ans:=1;
end;
if (a[i]=']') then
if now[top]='[' then
top:=top-1
else
begin
write('Wrong');
ans:=1;
end;
i:=i+1;
end;
if ans=0 then write('OK');
end.
哪里错了?
1个回答 分类:综合 2014-11-27

问题解答:

我来补答
首先 建议用for循环写 for i:=1 to length(a) do
还有 在循环中输出‘Wrong’后最好 break;
致命之处在于 if语句 if (a[i]='(') and (a[i]='[') 应该是 if (a[i]='(') or (a[i]='[')
同时 第二个 ‘wrong’ 应是 ‘Wrong’
 
 
展开全文阅读
剩余:2000