给你一个字符串 sequence ,如果字符串 word 连续重复 k 次形成的字符串是 sequence 的一个子字符串,那么单词 word 的 重复值为 k 。单词 word 的 最大重复值 是单词 word 在 sequence 中最大的重复值。如果 word 不是 sequence 的子串,那么重复值 k 为 0 。
给你一个字符串 sequence 和 word ,请你返回 最大重复值 k 。
示例 1:
输入:sequence = "ababc", word = "ab"
输出:2
解释:"abab" 是 "ababc" 的子字符串。
示例 2:
输入:sequence = "ababc", word = "ba"
输出:1
解释:"ba" 是 "ababc" 的子字符串,但 "baba" 不是 "ababc" 的子字符串。
示例 3:
输入:sequence = "ababc", word = "ac"
输出:0
解释:"ac" 不是 "ababc" 的子字符串。
记录 word 长度为 n,然后直接遍历 sequence ,当 sequence 第 i 位与 word 第一位相同时开始比较 sequence 中 [i, i+n) 子字符串与word 是否相同,如果相同,相同次数 ans 加一,并继续比较 sequence 再 [i+n, i+2n) 子串与 word 是否相同;如果不同停止比较,并且看当前相同次数 ans 是否为最大值。遍历完成 sequence 后返回最大值即可。
class Solution {
public int maxRepeating(String sequence, String word) {
int max = Integer.MIN_VALUE;
int n = word.length();
for (int i = 0; i < sequence.length(); i++) {
int index = i;
int ans = 0;
while (index + n <= sequence.length() && sequence.substring(index, index + n).equals(word)) {
ans++;
index += n;
}
max = Math.max(max, ans);
}
return max;
}
}
通过测试
