P3375 【模板】KMP字符串匹配

发布时间:2022-07-03 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了P3375 【模板】KMP字符串匹配脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

KMP算法

题目:https://www.luogu.COM.cn/PRoblem/P3375

    public static void kmp_seArch(String s1, String s2){
        if (s2.iSEMpty()) @R_304_2663@tem.out.println("-1");

        int n = s1.length();
        int m = s2.length();

        String ss1 = " "+s1;
        String ss2 = " "+s2;
        char str1[] = ss1.toCharArray();
        char str2[] = ss2.toCharArray();

        //next数组
        int next[] = new int[m + 1];
        for (int i = 2, j = 0; i <= m; i++){
            while (j > 0 && str2[i] != str2[j + 1]) j = next[j];
            if (str2[i] == str2[j + 1]) j++;
            next[i] = j;
        }

        //匹配过程
        for (int i = 1, j = 0; i <= n; i++){
            while (j > 0 &amp;& str1[i] != str2[j + 1]) j = next[j];
            if (str1[i] == str2[j + 1]) j++;
            if (j == m){
                System.out.println(i - m + 1);
                j = 0;
                i = i - m + 1;
            }
        }

 

脚本宝典总结

以上是脚本宝典为你收集整理的P3375 【模板】KMP字符串匹配全部内容,希望文章能够帮你解决P3375 【模板】KMP字符串匹配所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。