该函数在一个字符串中找到可能的最长的子字符串,

本文介绍了一个C#程序,该程序能够找出并打印出输入字符串中所有长度最长的连续重复字符序列。例如,在输入1223344555666555777788887777的情况下,输出结果为7777和8888。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如题,输出可能有多个最长字符串。

C# codes as below,

class Program

{

static void Main(string[] args)

{

string[] str = GetMaxString("1223344555666555777788887777");

foreach (string s in str)

{

Console.WriteLine(s);

}

Console.ReadKey();

}

static string[] GetMaxString(string str)

{

if (str == string.Empty || str == null)

{

return null;

}

//Set the default value of the string number is 1

int stringNumber=1;

//Set the default value of the string length is 1

int stringLength = 1;

char[] allChars = new char[str.Length];

//Set the default value of the first element is str[0]

allChars[0] = str[0];

char currentChar=str[0];

int count = 0;

for (int i = 0; i < str.Length; i++)

{

if (str[i] == currentChar)

{

count++;

if (count == stringLength)

{

//Set a bool mark to judge if the char has existed in the array allChars

bool ifExist = false;

//Go on a cycle to judge if the char has existed in the array allChars

for (int j = 0; j < stringNumber; j++)

{

if (allChars[j] == str[i])

{

ifExist = true;

}

}

//If this char hasn't been included in the array allChars, add it to the array.

if (!ifExist)

{

//Reset the number of the output strings

stringNumber++;

allChars[stringNumber - 1] = str[i];

}

}

else if (count > stringLength)

{

//Reset the number, length and value for the output strings

stringLength++;

stringNumber = 1;

allChars[0] = str[i];

}

}

else

{

//Reset current char's value

currentChar = str[i];

//Reset the value of count

count = 0;

//Recycle

i--;

}

}

//Name a string array

string[] result = new string[stringNumber];

//Set the value of the array

for (int i = 0; i < stringNumber; i++)

{

result[i] = new string(allChars[i], stringLength);

}

return result;

}

}

output:

7777

8888

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值