暴力搜索
测试用例范围很小,暴力搜索就能解决问题。
直接从sequence[i]
为起点判断重复子串的长度
当然暴力搜索也可以进行一些优化,比如可以加上一个数组记录从这个点开始的次数
class Solution {
public:
int maxRepeating(string sequence, string word) {
int res = 0;
for(int i = 0; i < sequence.size(); i++)
{
if(sequence[i] != word[0])
continue;
int k = i;
int j = 0;
int count = 0;
while(k < sequence.size() && sequence[k] == word[j])
{
k++;
j++;
if(j == word.size())
{
j = 0;
count++;
}
}
res = max(res, count);
}
return res;
}
};
KMP
使用暴力搜索后,发现可以对搜索的过程进行优化,对搜索数组中的子串最先想到的当然是KMP。顺便复习了一下KMP算法
class Solution {
public:
int maxRepeating(string sequence, string word) {
vector<int> next(word.size());
int j = -1;
next[0] = j;
for(int i = 1; i < word.size(); i++)
{
while(j != -1 && word[j + 1] != word[i])
j = next[j];
if(word[j + 1] == word[i])
j++;
next[i] = j;
}
vector<int> dp(sequence.size(), 0);
j = -1;
int res = 0;
for(int i = 0; i < sequence.size(); i++)
{
while(j != -1 && word[j + 1] != sequence[i])
j = next[j];
if(word[j + 1] == sequence[i])
j++;
if(j + 1 == word.size())
{
dp[i] = (i >= word.size() ? dp[i - word.size()] : 0) + 1;
j = next[j];
res = max(res, dp[i]);
}
}
return res;
}
};