zoukankan      html  css  js  c++  java
  • P3375 【模板】KMP字符串匹配

    KMP算法

    题目:https://www.luogu.com.cn/problem/P3375

        public static void kmp_search(String s1, String s2){
            if (s2.isEmpty()) System.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 && 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;
                }
            }
  • 相关阅读:
    css定位
    题解 P2345 【奶牛集会】
    浅谈主席树
    浅谈Manacher算法
    CSP2019 游记
    P5025 [SNOI2017]炸弹
    浅谈2-SAT
    DAY 5模拟赛
    DAY 3
    Luogu P2915 [USACO08NOV]奶牛混合起来
  • 原文地址:https://www.cnblogs.com/wltree/p/15369004.html
Copyright © 2011-2022 走看看