美好的一天,我编写了应该计算字符串中不同字符的代码,我的代码已经过数次输入测试,但无法计算此输入中的字符:
zcinitufxoldnokacdvtmdohsfdjepyfioyvclhmujiqwvmudbfjzxjfqqxjmoiyxrfsbvseawwoyynn
它具有将近80个字符,Pascal可以读取的最大字符串的长度为256个字符。我找不到更好的算法来解决此问题,因此,我正在寻找该领域专家或任何愿意分享知识的人员的帮助。
我猜我的代码在每个循环中都跳了一个字符。
这是我的代码:
function freq(char: char; username : String): Integer;
var
i, auxfreq: Integer;
begin
auxfreq:= 0;
for i:= 1 to length(username) do
if char = username[i] then
auxfreq:= auxfreq + 1;
//writeln(freq);
freq:= auxfreq;
end;
function OddUserName(username : String): Boolean;
var
usernameaux : String;
length_usernameaux, i : Integer;
Result : Boolean;
begin
Result:= false;
usernameaux:= username;
i:= 0;
repeat
i +=1;
length_usernameaux:= length(usernameaux);
if freq(usernameaux[i], usernameaux) <> 1 then
delete(usernameaux, i, 1);
until i = length_usernameaux;
// length(usernameaux) is supposed to be the number of the distinct characters.
{if length(usernameaux) mod 2 <> 0 then // you will have to ignore this.
Result:= true; // odd}
//writeln(usernameaux);
//writeln(length(usernameaux));
OddUserName:= Result; // ignore this too
end;
衷心感谢您的帮助。
您不能正确考虑字符串的delete()
字符长度变化。
如果username
为空,则由于repeat
循环尝试访问索引1(不存在)中的字符,最终将访问无效字符。实际上,您最终陷入一个无穷循环,因为从1开始并向上递增,但始终为0,所以i = length_usernameaux
始终为False (至少循环会一直运行,直到溢出到负值,最后递增回为0,但是那时您很可能在发生这种情况之前就已经崩溃了代码)。i
length_usernameaux
i
如果username
不为空,则i
在每次循环迭代时递增,当在处的字符时将跳过下delete()
一个字符i
。i
每当一个字符delete()
'd时,它都需要保持在相同的索引处,因为下一个字符将向下滑动以占据刚好delete
'd字符的索引。增量i
只有当不delete()
“荷兰国际集团的人物。
尝试以下方法:
function freq(charToFind: char; username : String): Integer;
var
i, auxfreq: Integer;
begin
auxfreq := 0;
for i := 1 to Length(username) do
begin
if charToFind = username[i] then
auxfreq := auxfreq + 1;
end;
//writeln(freq);
freq := auxfreq;
end;
function OddUserName(username : String): Boolean;
var
usernameaux : String;
length_usernameaux, i : Integer;
Result : Boolean;
begin
Result := false;
usernameaux := username;
length_usernameaux := Length(usernameaux);
i := 1;
while i <= length_usernameaux do
begin
if freq(usernameaux[i], usernameaux) > 1 then
begin
Delete(usernameaux, i, 1);
length_usernameaux := length_usernameaux - 1;
end else
begin
i = i + 1;
end;
end;
// length_usernameaux is supposed to be the number of the distinct characters.
{if length_usernameaux mod 2 <> 0 then // you will have to ignore this.
Result := true; // odd}
//writeln(usernameaux);
//writeln(length_usernameaux);
OddUserName := Result; // ignore this too
end;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句