我的老师希望我对括号进行随机排序。 我试图自己解决这个问题...但是,我发现我的解决方案不好,希望有人有更好的主意。
该字符串仅包含以下字符:()[] {} ... 因此,我首先检查了字符串的长度,然后使大小写语句对每个字符进行计数,以将数字保存在变量中。 之后,我使用变量中的值来获取所需的输出。
program counter;
uses SysUtils, crt;
var
character: String;
k1_open,k2_open,k3_open,k1_closed,k2_closed,k3_closed : Integer;
i : Integer;
begin
writeln('sort brackets (1. Version)');
write('Input: ');readln(character);
for i := 1 to length(character) do
begin
case character[i] of
'(' : k1_open := k1_open + 1;
'[' : k2_open := k2_open + 1;
'{' : k3_open := k3_open + 1;
')' : k1_closed := k1_closed + 1;
']' : k2_closed := k2_closed + 1;
'}' : k3_closed := k3_closed + 1;
end;
end;
if (k1_open = 1) and (k1_closed = 1) then begin
write('()');
end else if (k1_open = 2) and (k1_closed = 2) then begin
write('()()');
end else if (k1_open = 3) and (k1_closed = 3) then begin
write('()()()');
end;
if (k2_open = 1) and (k2_closed = 1) then begin
write('[]');
end else if (k2_open = 2) and (k2_closed = 2) then begin
write('[][]');
end else if (k2_open = 3) and (k2_closed = 3) then begin
write('[][][]');
end;
if (k3_open = 1) and (k3_closed = 1) then begin
write('{}');
end else if (k3_open = 2) and (k3_closed = 2) then begin
write('{}{}');
end else if (k3_open = 3) and (k3_closed = 3) then begin
write('{}{}{}');
end;
end.
示例:
Input: [{])]}(
Output: {}[]()
Input: [(}{[])}(]{)
Output:{}{}[][]()()
Input: [][}}](
Output: Error - brackets do not match.
正如我所说-我有想要的结果...但是我认为执行效果很差。 但是我找不到更好的解决方案。
希望您能帮助我-谢谢!
答案 0 :(得分:0)
变量是全局变量,因此它们将被初始化为0,但是否则,您可能希望将 k1_open 等设置为0。
您可以改进如下代码:
if (k1_open = 1) and (k1_closed = 1) then begin
write('()');
end else if (k1_open = 2) and (k1_closed = 2) then begin
write('()()');
end else if (k1_open = 3) and (k1_closed = 3) then begin
write('()()()');
end;
if (k2_open = 1) and (k2_closed = 1) then begin
write('[]');
end else if (k2_open = 2) and (k2_closed = 2) then begin
write('[][]');
end else if (k2_open = 3) and (k2_closed = 3) then begin
write('[][][]');
end;
if (k3_open = 1) and (k3_closed = 1) then begin
write('{}');
end else if (k3_open = 2) and (k3_closed = 2) then begin
write('{}{}');
end else if (k3_open = 3) and (k3_closed = 3) then begin
write('{}{}{}');
end;
变成这样:
if (k1_open = k1_closed) and
(k2_open = k2_closed) and
(k3_open = k3_closed) then
begin
for i := 1 to k1_open do
Write('()');
for i := 1 to k2_open do
Write('[]');
for i := 1 to k3_open do
Write('{}');
Writeln;
end
else
Writeln('Brackets do not match')
end.
改进的版本也可以处理比每种括号中的三个大的数字。