Leetcode 1668. Maximum Repeating Substring
1668. Maximum Repeating Substring
Given a string sequence
and a string word
, return the maximum number of times word
can be repeated in sequence
as a substring.
word
overlap within the sequence
?
word
when it is repeated.sequence
and word
?
sequence
and word
doesn’t exceed (100) characters.sequence
or word
be empty strings?
sequence
nor word
would be empty.Concatenate word
Multiple Times: Create increasingly longer strings of repeated word
(e.g., word
, word+word
, word+word+word
, etc.).
Check Substring Existence: For each concatenated string, check if it is a substring of sequence
.
Optimize Checking: Stop as soon as the concatenated string is no longer found in sequence
.
#include <iostream>
#include <string>
using namespace std;
int maxRepeating(string sequence, string word) {
int maxRepeat = 0;
string repeatedWord = word;
while (sequence.find(repeatedWord) != string::npos) {
maxRepeat++;
repeatedWord += word;
}
return maxRepeat;
}
int main() {
string sequence = "ababc";
string word = "ab";
cout << "Maximum repeating: " << maxRepeating(sequence, word) << endl;
return 0;
}
repeatedWord
is within the length of sequence
. Suppose n
is the length of sequence
and m
is the length of word
.k
th concatenated string and checking for a substring takes (O(n)) in the worst case. However, the overall complexity is dominated by the increasing size of repeatedWord
.word
to a temporary repeatedWord
string.find
to check if repeatedWord
is in sequence
.This ensures that we correctly identify the maximum number of times word
can be repeated consecutively within sequence
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?