最大的子串由相同的字符组成

Han*_*ody 3 c# algorithm

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

例如,如果我们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;
    }
Run Code Online (Sandbox Code Playgroud)

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

先感谢您.

Dmi*_*nko 6

既然你想要"最大的子串..."让我们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);
}
Run Code Online (Sandbox Code Playgroud)

....

// "ccccc"
String result = GetMaxSubstring("aaacccccdefffgg");
// 5
int length = result.Length;
Run Code Online (Sandbox Code Playgroud)