gpt4 book ai didi

c# - 相同字符组成的最大子串

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:03:35 24 4
gpt4 key购买 nike

我想开发一种方法,该方法将返回由作为参数传递的字符串中相同字符组成的最大子字符串的长度,但不使用任何 .NET 库

例如,如果我们将 aaacccccdefffgg 作为参数传递,最大的子字符串是 ccccc 并且方法应该返回 5。

这是我的工作解决方案:

public static int GetMaxSubstringLenght(char[] myArray)
{
int max = 0;

for (int i = 0; i < myArray.Length-1; i++)
{
if (myArray.Length == 0)
{
return 0;
}
else
{
int j = i + 1;
int currentMax = 1; // string has some value, so we start with 1
while (myArray[i] == myArray[j])
{
currentMax++;
if (max < currentMax)
{
max = currentMax;
}
j++;
}
}
}
return max;
}

上面的代码将返回预期的结果,但在 for 循环 中会有一些我想避免的不必要的迭代。在第一次迭代中,当 i=0 时,它将比较它直到 j=2 ,然后退出 while 循环 并在 开始第二次迭代code>for 循环[1] 索引处的那个与 [2] 进行比较,我们在之前的迭代中已经这样做了。所以基本上,当第一次迭代是完成,下一个应该从j的最后一个值开始。我怎样才能做到这一点?

提前致谢。

最佳答案

既然你想要“最大的子串......”让我们把 String 作为参数并返回 String

public static String GetMaxSubstring(String value) {
if (String.IsNullOrEmpty(value))
return "";

int bestCount = 0;
char bestChar = '\0';

int currentCount = 0;
char current = '\0';

for (int i = 0; i < value.Length; ++i) {
if ((i == 0) || (value[i] != current))
currentCount = 0;

currentCount += 1;
current = value[i];

if (currentCount > bestCount) {
bestCount = currentCount;
bestChar = current;
}
}

return new String(bestChar, bestCount);
}

....

// "ccccc"
String result = GetMaxSubstring("aaacccccdefffgg");
// 5
int length = result.Length;

关于c# - 相同字符组成的最大子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37703724/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com