Entre las diversas formas de escribir el algoritmo KMP, la más corta y fácil de entender

código directamente

import java.io.*;

public class Main {
    
    
    static  int N=100010;
    static int M=1000010;
    static int n=0;
    static  int m=0;
    static  char []p=new char[N];
    static  char []s=new char[M];
    static int ne[]=new int[N];
    public static void main (String[] args) throws IOException {
    
    
        BufferedReader br=new BufferedReader (new InputStreamReader (System.in));
        BufferedWriter bw=new BufferedWriter (new OutputStreamWriter (System.out));
         n=Integer.parseInt (br.readLine ());
        char cs[]=br.readLine ().toCharArray ();
        System.arraycopy (cs,0,p,1,n);
        m=Integer.parseInt (br.readLine ());
        cs=br.readLine ().toCharArray ();
        System.arraycopy (cs,0,s,1,m);

        /**
         * 求next数组
         * next数组是用来在匹配不成功的时候,将匹配串的指针向左退的时候用的。具体退多少看ne[j]是多少
         * next数组的含义是在匹配串中,前缀子串和后缀子串最多能相等的长度是多少
         * 意思就是我向后退了以后,还能利用到之前匹配的信息,下一次在匹配的时候可以不用再把之前匹配过的在匹配一遍
         *
         * i为什么从2开始? 因为0,1的next数组值全为0
         */
        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;
        }

        //匹配过程
        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){
    
    
                bw.write (i-n+" ");
                //匹配成功了往后退一个 其实不要下面这行也行
                j=ne[j];
            }

        }
        bw.flush ();

    }
}

Supongo que te gusta

Origin blog.csdn.net/guankunkunwd/article/details/122705716
Recomendado
Clasificación