Reputation:
How do I return the index of d in the following string "abbcccddddcccbba"
I know how to find the longest substring but retruning the starting index is eluding me.
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???
}
Upvotes: 2
Views: 205
Reputation: 2718
I tested the following and I think it is the most efficient way:
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;
}
Upvotes: 4