LeetCode - Algorithms - 1668. Maximum Repeating Substring

Problem

1668. Maximum Repeating Substring

Java

Brute-force loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
private int countByPrefix(String sequence, String word) {
int maxCount = 0;
int tempCount = 0;
int word_len = word.length();
for (int i = 0; i <= sequence.length() - word_len; i++) {
String str = sequence.substring(i, i + word_len);
if (str.equals(word)) {
tempCount++;
i += word_len - 1;
} else {
tempCount = 0;
}
if (tempCount > maxCount)
maxCount = tempCount;
}
return maxCount;
}

private int countBySuffix(String sequence, String word) {
int maxCount = 0;
int tempCount = 0;
int word_len = word.length();
for (int i = sequence.length(); i > word_len - 1; i--) {
String str = sequence.substring(i - word_len, i);
if (str.equals(word)) {
tempCount++;
i = i - word_len + 1;
} else {
tempCount = 0;
}
if (tempCount > maxCount)
maxCount = tempCount;
}
return maxCount;
}

public int maxRepeating(String sequence, String word) {
int maxCount_prefix = countByPrefix(sequence, word);
int maxCount_suffix = countBySuffix(sequence, word);
return maxCount_prefix > maxCount_suffix ? maxCount_prefix : maxCount_suffix;
}
}

Submission Detail

  • 212 / 212 test cases passed.
  • Runtime: 1 ms, faster than 82.84% of Java online submissions for Maximum Repeating Substring.
  • Memory Usage: 37.5 MB, less than 50.50% of Java online submissions for Maximum Repeating Substring.

© java short easy to understand

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int maxRepeating(String sequence, String word) {
int count = 0;
String pat = word;
while (sequence.contains(pat)) {
count++;
pat += word;
}
return count;
}
}

Submission Detail

  • 212 / 212 test cases passed.
  • Runtime: 1 ms, faster than 82.48% of Java online submissions for Maximum Repeating Substring.
  • Memory Usage: 37.6 MB, less than 50.74% of Java online submissions for Maximum Repeating Substring.