I am trying to solve this question: Write a function that finds the zero index of the longest path in the string. A run is a sequential sequence of the same symbol. If more than one run with the same length is running, return the index of the first.
For example, IndexOfLongestRun ("abbcccddddcccbba") should return 6 because the longest run is dddd, and it first appears in index 6.
After what I have done:
private static int IndexOfLongestRun(string str) { char[] array1 = str.ToCharArray(); //Array.Sort(array1); Comparer comparer = new Comparer(); int counter =1; int maxCount = 0; int idenxOf = 0; for (int i =0; i<array1.Length-1 ; i++) { if (comparer.Compare(array1[i],array1[i+1]) == 0) { counter++; } else { if(maxCount < counter) { maxCount = counter; idenxOf = i - counter + 1; } counter = 1; } } return idenxOf ; } } public class Comparer : IComparer<char> { public int Compare(char firstChar, char nextChar) { return firstChar.CompareTo(nextChar); } }
The problem is that when I get to the last index, for example, "abbccaaaaaaaaaa" which is in this case, and when i=14 (taking this line as an example), and when i<array1.Length-1 statment is false, the for loop translates directly into return indexOf; and returns the wrong index, I'm trying to figure out how to get forloop to continue the implementation so that idenxOf can be changed to the right index. Any help please?
c # algorithm icomparer
Kob_24
source share