Skip to content

Commit 431d9de

Browse files
solves maximum repeating substring
1 parent e6daec3 commit 431d9de

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -411,7 +411,7 @@
411411
| 1652 | [Defuse the Bomb](https://leetcode.com/problems/defuse-the-bomb) | [![Java](assets/java.png)](src/DefuseTheBomb.java) | |
412412
| 1656 | [Design an Ordered Stream](https://leetcode.com/problems/design-an-ordered-stream) | [![Java](assets/java.png)](src/DesignAnOrderedStream.java) | |
413413
| 1662 | [Check If Two String Arrays are Equivalent](https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent) | [![Java](assets/java.png)](src/CheckIfTwoStringArraysAreEquivalent.java) | |
414-
| 1668 | [Maximum Repeating Substring](https://leetcode.com/problems/maximum-repeating-substring) | | |
414+
| 1668 | [Maximum Repeating Substring](https://leetcode.com/problems/maximum-repeating-substring) | [![Java](assets/java.png)](src/MaximumRepeatingSubString.java) | |
415415
| 1672 | [Richest Customer Wealth](https://leetcode.com/problems/richest-customer-wealth) | | |
416416
| 1678 | [Goal Parser Interpretation](https://leetcode.com/problems/goal-parser-interpretation) | | |
417417
| 1684 | [Count the Number of Consistent Strings](https://leetcode.com/problems/count-the-number-of-consistent-strings) | | |

src/MaximumRepeatingSubString.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
public class MaximumRepeatingSubString {
2+
public int maxRepeating(String sequence, String word) {
3+
int result = 0, index = 0;
4+
while (index < sequence.length()) {
5+
int matchIndex = sequence.indexOf(word, index);
6+
if (matchIndex == -1) break;
7+
int k = 0;
8+
for (int i = matchIndex + word.length() ; i < sequence.length() ; i += word.length(), k++) {
9+
if (!areEqual(sequence, word, i)) break;
10+
}
11+
result = Math.max(result, 1 + k);
12+
index = matchIndex + 1;
13+
}
14+
return result;
15+
}
16+
17+
private boolean areEqual(String text, String pattern, int startIndex) {
18+
if (pattern.length() > text.length() - startIndex) return false;
19+
for (int i = startIndex ; i < text.length() && i - startIndex < pattern.length() ; i++) {
20+
if (text.charAt(i) != pattern.charAt(i - startIndex)) return false;
21+
}
22+
return true;
23+
}
24+
}

0 commit comments

Comments
 (0)