1668. 最大重复子字符串
方法一:暴力枚举
class Solution {
public int maxRepeating(String sequence, String word) {
char[] ch1 = sequence.toCharArray();
int res = 0;
StringBuilder sb = new StringBuilder(word);
while(sb.length() <= sequence.length()) {
if (isEqual(ch1, sb.toString().toCharArray())) {
res ++;
sb.append(word);
} else {
break;
}
}
return res;
}
public boolean isEqual(char[] ch1, char[] ch2) {
if (ch2.length > ch1.length){
return false;
}
for(int k = 0; k < ch1.length - ch2.length + 1; k ++) {
int i = k, j = 0;
while (i < ch1.length && j < ch2.length) {
if (ch1[i] == ch2[j]) {
i++;
j++;
}else{
break;
}
}
if (j == ch2.length) return true;
}
return false;
}
}
方法二:DP + KMP
KMP模板
for (int i = 2, j = 0; i <= m; i ++ )
{
while (j > 0 && p[i] != p[j + 1]) j = ne[j];
if (p[i] == p[j + 1]) j ++ ;
ne[i] = j;
}
for (int i = 1, j = 0; i <= n; i ++ )
{
while (j > 0 && s[i] != p[j + 1]) j = ne[j];
if (s[i] == p[j + 1]) j ++ ;
if (j == m)
{
j = ne[j];
}
}
class Solution {
public int maxRepeating(String sequence, String word) {
int n = word.length();
int m = sequence.length();
char[] s = (" " + sequence).toCharArray();
char[] p = (" " + word).toCharArray();
int res = 0;
if (p.length > s.length) {
return res;
}
int[] ne = new int[105];
for(int i = 2, j = 0; i <= n; i++){
while(j != 0 && p[i] != p[j+1]) j = ne[j];
if(p[i] == p[j + 1]) j++;
ne[i] = j;
}
int[] dp = new int[105];
for(int i = 1, j = 0; i <= m; i++){
while(j != 0 && s[i] != p[j+1]) j = ne[j];
if(s[i] == p[j+1]) j++;
if(j == n){
dp[i] = (i >= n ? dp[i - n] : 0) + 1;
j = ne[j];
}
}
return Arrays.stream(dp).max().getAsInt();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧