如果只是英文字符,你可能只是分配一個數組來保持每個字符的計數。在這種情況下,代碼可能看起來像這樣。
我用Delphi寫了這個。我希望它在你的帕斯卡風味中也可以。
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
。
一個並不那麼可怕的效果,但容易理解的方法將貫穿字符串,如果字符不存在,將它添加到值爲1的冠詞,如果它存在增加值爲1 for人物。然後一次通過字符串 - 你有每個字符的計數。 還有很多其他的方式 - 所以這只是一個容易做 –
計數是微不足道的,上面的代碼幾乎是無用的,但你。你需要的第一件事就是存儲角色的次數和看到的次數。如果這是香草pascal,你需要寫或借用一些東西來做到這一點。 –