LeetCode原题:1668. 最大重复子字符串
class Solution {
public int maxRepeating(String sequence, String word) {
// 模式串长度大于原字符串,返回0
if (word.length() > sequence.length()) {
return 0;
}
// 原字符串中一个模式串都没有,返回0
if (sequence.indexOf(word) == -1) {
return 0;
}
int index = sequence.indexOf(word);
// 记录从每个位置开始的模式串连续重复的次数
int repeat = 0;
// 记录模式串最大连续重复次数
int maxRepeat = 0;
for (int i = index; i <= sequence.length() - word.length(); i++) {
// 从位置i开始(包含i以及i后面所有的位置)截取到字符串最后的位置,字符串长度已经比目前最长的连续模式串长度小,不需要继续向下遍历计算
if (sequence.length() - i <= maxRepeat * word.length()) {
break;
}
repeat = 0;
// 遍历检查从位置i开始的模式串连续重复的次数
for (int j = i, k = j + word.length(); k <= sequence.length(); j += word.length(), k += word.length()) {
if (sequence.substring(j, k).equals(word)) {
repeat++;
} else {
break;
}
}
// 每次检查完都更新最大连续重复次数
maxRepeat = Math.max(maxRepeat, repeat);
}
return maxRepeat;
}
}