Maximum Repeating Substring

easy string substring search brute force

Problem

A string word is k-repeating in sequence if word concatenated k times is a substring of sequence. The maximum k-repeating value is the largest k for which this holds; if word is not a substring of sequence at all, the answer is 0. Return that maximum value.

Inputsequence = "ababc", word = "ab"
Output2
"abab" (ab twice) appears in "abab​c", so k = 2. "ababab" does not, so 2 is the max.
Inputsequence = "ababc", word = "ac"
Output0
"ac" is not a substring of "ababc", so the answer is 0.

def max_repeating(sequence, word):
    k = 0
    candidate = word
    while candidate in sequence:
        k += 1
        candidate += word
    return k
function maxRepeating(sequence, word) {
  let k = 0;
  let candidate = word;
  while (sequence.includes(candidate)) {
    k += 1;
    candidate += word;
  }
  return k;
}
int maxRepeating(String sequence, String word) {
    int k = 0;
    String candidate = word;
    while (sequence.contains(candidate)) {
        k += 1;
        candidate += word;
    }
    return k;
}
int maxRepeating(string sequence, string word) {
    int k = 0;
    string candidate = word;
    while (sequence.find(candidate) != string::npos) {
        k += 1;
        candidate += word;
    }
    return k;
}
Time: O(n · K) Space: O(n)