Site Search:

Longest Repeating string

Problem

given a string, find the start index and the length of the longest repeating substring.

For example, 
input: aaabcdd
output: {0, 3}
input: abcddd
output: {3, 3}

Solution

we can scan from left to right, once meet a changing character, we update the max length and the start index. 

public class LongestRepeat {
    public static int[] longest(String input) {
    int longestStart = -1;
    int longestLength = -1;
    int start = 0;
    int N = input.length();
    for(int i = 0; i < N-1; i++) {
      //111100
      //.  3
      if(input.charAt(i+1) != input.charAt(i)) {
        if(longestLength < i - start + 1) {
          longestLength = i - start + 1;
          longestStart = start;
        }
        start = i+1;
      }
    }
    if(N-start > longestLength) {
      longestLength = N-start;
      longestStart = start;
    }
    return new int[]{longestStart, longestLength};
  }
  public static void main(String...args) {
    for(int i : longest("aaabcdd")) {
      System.out.print(i + " ");
    }
    System.out.println();
    for(int i : longest("11001111101111000AAbbbbbb")) {
      System.out.print(i + " ");
    }
    System.out.println();
  }
}

Time complexity O(N), space complexity O(1).