如何在以下字符串"abbcccddddcccbba"
中返回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???
}
答案 0 :(得分:4)
我测试了以下内容,我认为这是最有效的方式:
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;
}