For a string sequence, a string word is k-repeating if word
concatenated k times is a substring of sequence. The word’s
maximumk-repeating value is the highest value k where word is
k-repeating in sequence. If word is not a substring of sequence,
word’s maximum k-repeating value is 0.
Given strings sequence and word, return themaximumk-repeating value of word in sequence.
The key idea is to check how many times we can repeat the word and still find it as a substring in the sequence. We keep increasing the count until the repeated word is no longer a substring.
classSolution {
public:int maxRepeating(string sequence, string word) {
int k =0;
string t = word;
while (sequence.find(t) != string::npos) {
k++;
t += word;
}
return k;
}
};
1
2
3
4
5
6
7
8
9
funcmaxRepeating(sequencestring, wordstring) int {
k:=0t:=wordforstrings.Contains(sequence, t) {
k++t+=word }
returnk}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
publicintmaxRepeating(String sequence, String word) {
int k = 0;
String t = word;
while (sequence.contains(t)) {
k++;
t += word;
}
return k;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funmaxRepeating(sequence: String, word: String): Int {
var k = 0var t = word
while (sequence.contains(t)) {
k++ t += word
}
return k
}
}
1
2
3
4
5
6
7
8
classSolution:
defmaxRepeating(self, sequence: str, word: str) -> int:
k =0 t = word
while t in sequence:
k +=1 t += word
return k
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnmax_repeating(sequence: String, word: String) -> i32 {
letmut k =0;
letmut t = word.clone();
while sequence.contains(&t) {
k +=1;
t +=&word;
}
k
}
}
⏰ Time complexity: O(n * m * k), where n is the length of sequence, m is the length of word, and k is the maximum number of repetitions. Each check for substring can take up to O(n), and we do this up to k times, where k can be up to n/m.
🧺 Space complexity: O(m * k), for the temporary string t which grows by m each time up to k times.