Description
假设表达式中允许包含两种括号:圆括号和方括号,其嵌套的顺序随意,如([ ]())或[([ ][ ])]等为正确的匹配,[(
])或([ ]( )或 ( ( ) ) )均为错误的匹配。
现在的问题是,要求检验一个给定表达式中的括弧是否正确匹配?
输入一个只包含圆括号和方括号的字符串,判断字符串中的括号是否匹配,匹配就输出 “OK”
,不匹配就输出“Wrong”。
Input
输入仅一行字符(字符个数小于255)
Output
匹配就输出 “OK” ,不匹配就输出“Wrong”。
Sample Input
[([][])]
Sample Output
OK
解题思路:先以字符串的形式读入,然后进行判断,如果是’[‘或者’(‘就入栈,如果是’ )’或者’]’就进行判断,如果它符合要求就出栈,不然就返回false,最后输出OK或者Wrong即可。
程序:
const
maxn=20;
var
c:string;
function judge(c:string):boolean;
var
s:array[1..maxn]of char;
top,i:longint;
ch:char;
begin
judge:=true;
top:=0;
for i:=1 to length(c) do
begin
ch:=c[i];
case ch of
'[','(':begin inc(top); s[top]:=ch; end;
']',')':if ((s[top]='(') and (ch=')') or (s[top]='[') and (ch=']')) and (top>0) then dec(top) else begin judge:=false; exit; end;
end;
end;
if top<>0 then judge:=false;
end;
begin
readln(c);
if judge(c) then writeln('OK') else writeln('Wrong');
end.