1668. 最大重复子字符串

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();
    }
}
posted @   Eiffelzero  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示