暴力解法可以过,这大概是这道题简单的唯一原因了吧…
直接挨个试,找word的连续最大重复次数
class Solution {
public int maxRepeating(String sequence, String word) {
int n=sequence.length(),m=word.length(),max=0;
for(int i=0;i<=n-m;i++){
int res=0,j=i;
while(j+m<=n&&sequence.substring(j,j+m).equals(word)){
res++;
j+=m;
}
max=Math.max(max,res);
}
return max;
}
}
时间复杂度: O ( n 2 m ) O(n^2m) O(n2m)
空间复杂度: O ( 1 ) O(1) O(1)
序列dp入门题
将sequence的每一个位置作为结束位置,判断前面的m个字符是否恰好是字符串word。
class Solution {
public int maxRepeating(String sequence, String word) {
int n=sequence.length(),m=word.length(),max=0;
int[] dp=new int[n+1];
for(int i=m;i<=n;i++){
if(sequence.substring(i-m,i).equals(word))
dp[i]=dp[i-m]+1;
max=Math.max(max,dp[i]);
}
return max;
}
}
时间复杂度: O ( n ∗ m ) O(n*m) O(n∗m)
空间复杂度: O ( n ) O(n) O(n)