Java code to find index of longest repeated letters in a string

Here’s the Java code to find index of the longest consecutive sequence of repeated letters in a string. If there is more than one run with the same length, the index of the first one is returned.
For example, if the string is(“bbbccffffiiiffff”), the program should return 5 as the longest sequence is ffff and it first appears on index 5.

public class Run {
    public static int indexOfLongestRun(String str) {
        int finalIndex = 0;
        char[] array = str.toCharArray();
        if (array.length >0) {
            char c = array[0];
            int len = 1;
            int longest = 0;
            int index = 0;
            for (int i = 1; i < array.length; i++) {
                if (c == array[i]) {
                    len++;
                    if (len > longest) {
                        longest = len;
                        finalIndex = index;
                    }
                } else if (c != array[i]) {
                    len = 1;
                    index = i;
                }
                c = array[i];
            }
        }
        return finalIndex;
    }

    public static void main(String[] args) {
        System.out.println(indexOfLongestRun("abbcccddddcccbba"));
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *