问题描述
早上好, 我已经编写了应该计算字符串中不同字符的代码,我的代码已经过数次输入测试,但无法计算此输入中的字符:
Tag
它具有将近80个字符,Pascal可以读取的最大字符串的长度为256个字符。 我找不到更好的算法来解决这个问题,因此,我正在寻求该领域专家或任何愿意分享知识的人的帮助。
这是我的代码:
zcinitufxoldnokacdvtmdohsfdjepyfioyvclhmujiqwvmudbfjzxjfqqxjmoiyxrfsbvseawwoyynn
衷心感谢您的帮助。
解决方法
如果只需要获取某个字符串中不同字符的数量,则可以使用以下简单方法:
function CountDistinctCharacters(InputString: string): Integer;
var I: Integer;
//String for storing all distinct characters
DistinctChars: string;
begin
//Loop trough every character in input string
for I := 1 to Length(InputString) do
begin
//Use Pos function to find position of specific character in DistinctChars string
//Function returns 0 if character is not found
if Pos(InputString[I],DistinctChars) = 0 then
begin
//If character isn't found in DistinctChars string add it to it
DistinctChars := DistinctChars+InputString[I];
end;
end;
//Finaly check the lenght of DistinctChars string to get the number of distinct character
//found and return it as function result
Result := Length(DistinctChars);
end;
如果您还需要输入字符串中存在哪些字符的信息,则可以代替使用本地DistinctChars
字符串变量,将字符串作为var pamaeter传递给函数,如下所示:
//Pass external string as var parameter to your function in order to allow function to
//fill it with all distinct characters
function CountDistinctCharacters(InputString: string; var DistinctChars: string): Integer;
var I: Integer;
begin
//Loop trough every character in input string
for I := 1 to Length(InputString) do
begin
//Use Pos function to find position of specific character in DistinctChars string
//Function returns 0 if character is not found
if Pos(InputString[I],DistinctChars) = 0 then
begin
//If character isn't found in DistinctChars string add it to it
DistinctChars := DistinctChars+InputString[I];
end;
end;
//Finaly check the lenght of DistinctChars string to get the number of distinct character
//found and return it as function result
Result := Length(DistinctChars);
end;
但是,如果您还想知道输入字符串中每个字符有多少个信息,那么您将不得不为结果使用某种数据结构,该结构允许存储诸如TDictionary之类的数据对或每个记录存储在其中的记录数组对信息(字符和出现次数)。
, delete()
个字符串中的字符时,您不能正确地考虑字符串的长度变化。
如果username
为空,则由于repeat
循环试图访问索引1处不存在的字符而导致访问无效字符。实际上,由于i = length_usernameaux
从1开始并向上递增,而i
始终为False,所以您最终陷入了一个无限循环,但是length_usernameaux
始终为0(至少,循环运行直到i
溢出到负值,并最终递增回到0,但到那时您可能已经使代码崩溃了。
如果username
不为空,则在每次循环迭代中增加i
,当{{1}时将跳过 next 字符。 }在delete()
处输入字符。每当输入i
时,i
就必须保持相同的索引,因为 next 字符将向下滑动以占据只是{{ 1}}。仅当未delete()
不是字符时才递增delete
。
尝试以下方法:
i
,
通过您的帮助,我设法解决了它。 我所做的就是删除重复的字符后将索引减少一。 像这样:
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
begin
delete(usernameaux,i,1);
i-=1; // <----- added
end;
until i = length_usernameaux;
if length(usernameaux) mod 2 <> 0 then
Result:= true; // odd
//writeln(usernameaux);
//writeln(length(usernameaux));
OddUserName:= Result;
end;