我的任务是连续显示最常用的字母。例如,如果你输入aabbbbccbbb,大多数重复的字符是B,它被使用了4次。关于同一个任务有一个非常相似的主题,但我不理解代码。 Most repeating character in a string
Program Task;
var s:string;
i,k,g,count:integer;
c:char;
begin
Readln(s);
g:=0;
while Length(s) > 0 do
begin
c := s[1];
i:=1;
while i<= Length(s) do
begin
If (c=s[i]) then
delete(s,i,1)
else
Inc(i);
If (c=s[i]) then
Inc(g);
end;
end;
Writeln(g);
Readln;
end.
我面临很多问题。首先是我不知道如何显示哪个字符最常用,其次是我不知道如何比较哪个重复字符最常用。 例如,如果我写aaaabbbc它会给我7的回答,因为有4xa和3xb。 所有的帮助都非常感谢。
答案 0 :(得分:0)
如果它只是英文字符,你可能只需要分配一个数组来保持每个字符的计数。在这种情况下,代码可能如下所示。
我是用Delphi写的。我希望它能在你的Pascal风格中发挥作用。
program Task;
{$APPTYPE CONSOLE} // For Delphi
var
s: string[50];
i: Integer;
Counters: array[Char] of Integer;
Highest: Char;
begin
// Initialize counters.
for i := 0 to 255 do
Counters[Char(i)] := 0;
s := 'aabbbbccbbb';
// Count the characters.
for i := 1 to Length(s) do
Inc(Counters[s[i]]);
// Find out which one is highest.
Highest := #0;
for i := 0 to 255 do
if Counters[Char(i)] > Counters[Highest] then
Highest := Char(i);
// Output that character and its count.
WriteLn('The highest character is ', Highest, ' with ', Counters[Highest], ' occurrences.');
ReadLn;
end.
在较少的学术设置中,使用这样的数组可能效率不高,因为它包含每个可能字符的计数器,包括那些根本不在字符串中出现的字符。这意味着,如果你想为unicode表中的每个可能的字符使用这个确切的代码,你的数组将是几兆字节(在现代计算机上仍然不是真正的问题,但仍然)。
您可以通过使用一种字典或列表来跟踪项目来改进此代码,因此您只需添加您找到的项目,但如果您必须自己编写,则会使您的程序相当有点大。
编辑:
根据评论中的要求:计算最长的后续字符范围:
program Task;
{$APPTYPE CONSOLE} // For Delphi
var
s: String;
i: Integer;
Longest: Integer;
Current: Integer;
LongestChar: Char;
begin
s := 'aabbbbccbbb';
Longest := 0;
Current := 0;
// Count the characters.
for i := 1 to Length(s) do
begin
Inc(Current);
// If it's the last char or the next char is going to be different, restart the counting.
if (i = Length(s)) or (s[i] <> s[i+1]) then
begin
if Current > Longest then
begin
Longest := Current;
LongestChar := s[i];
end;
Current := 0;
end;
end;
// Output that character and its count.
WriteLn('The highest character is ', LongestChar, ' with ', Longest, ' occurrences.');
ReadLn;
end.
Current > Longest
确保在多个字符序列具有相同长度的情况下返回第一个最长的序列。如果您想要最后一个序列,请更改为Current >= Longest
。