1668.最大重复子字符串
class Solution {
public int maxRepeating(String sequence, String word) {
//方法一
if(sequence.length() < 1 || sequence.length() < word.length()) return 0;
int res = 0;
String temp = word;
while(sequence.contains(temp)) { //如果sequence包含temp
temp += word; //temp再加一个word,让temp为word的连续字符串,并不断在sequence中判断是否存在temp
res++;
}
return res;
//方法二
if(sequence.length() < 1 || sequence.length() < word.length()) return 0;
int count = 0; //计算当前连续子串的最多个数
int res = 0; //保留最多的连续子串个数
int i = -word.length(); //i为上一个word的索引,这里假设初值为 -word.length()
int k = 0;
while(true) {
//得到word在sequence从 i+word.length() 索引开始第一次出现的索引
k = sequence.indexOf(word, i + word.length());
if(k == -1) break;
//如果两者相等,说明当前是连续子串,上一个word出现后紧接着就是下一个word
if(k == i + word.length()) {
count++; //令当前连续子串个数+1
i = k; //令上一个word的索引更新为这一个,即为 i+word.length()
} else { //说明连续子串中断
res = Math.max(res, count); //来判断是否为最长连续子串的个数
count = 0;
i = k - word.length(); //令i为当前word出现索引减去一个word的长度,以保证下一次循环时 i+word.length() 能等于当前word出现的索引
}
}
res = Math.max(res, count);
return res;
}
}