C# 最长子串的返回索引

C# 最长子串的返回索引,c#,string,C#,String,如何在下面的字符串abbccdddccbba中返回d的索引我知道如何找到最长的子字符串,但重新运行起始索引却让我不知所措 public static int IndexOfLongestRun(string str) { int currentIndex = 0; int finalIndex = 0; int longestOccurence = 0; for (int i = 0; i < str.Lengt

如何在下面的字符串abbccdddccbba中返回d的索引我知道如何找到最长的子字符串,但重新运行起始索引却让我不知所措

public static int IndexOfLongestRun(string str)
    {
        int currentIndex = 0;

        int finalIndex = 0;

        int longestOccurence = 0;

        for (int i = 0; i < str.Length - 1; i++)
        {
            if (str[i] == str[i + 1])
            {
                currentIndex++;
            }

            else
            {
                currentIndex = 1; 
            }

            if (longestOccurence < currentIndex)
            {
                longestOccurence = currentIndex;
            }
        }


        return str.IndexOf(str, longestOccurence); // return what???
    }

我测试了以下内容,我认为这是最有效的方法:

public static int IndexOfLongestRun(string str)
{
  if (string.IsNullOrEmpty(str)) return -1;

  int currentStartIndex = 0;
  int longestIndex = 0;
  int longestLength = 0;
  int currentLenght = 0;

  for (int i = 0; i < str.Length - 1; i++)
  {
    if (str[i] != str[i + 1])
    {
      currentStartIndex = i + 1;
      currentLenght = 1;
    }
    else
    {
      currentLenght++;
    }

    if (currentLenght > longestLength)
    {
      longestLength = currentLenght;
      longestIndex = currentStartIndex;
    }
  }

  return longestIndex;
}

我想,如果字符串为空,longestIndex的初始值应该是-1。我将编辑我的anser。但是,当检测到字符串为null或空时,我更希望立即返回-1。