JAVA KMP 純模板

Shie1d發表於2024-05-17

純模板 記憶使用~

import java.util.*;

class Main {

    static char[] s1;
    static char[] s2;
    static int[] next;
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        s1 = in.nextLine().toCharArray();
        s2 = in.nextLine().toCharArray();
        int m = s2.length;
        int n = s1.length;
        next = new int[m];
        getNext();
        //System.out.println(Arrays.toString(next));
        List<Integer> res = new ArrayList<>();
        int i = 0, j = 0;
        while(i < n){
            if(j == -1 || s1[i] == s2[j]){
                i++;
                j++;
            }else{
                j = next[j];
            }
            if(j == m){// 可重複匹配版本 單次匹配直接break
                res.add(i - j);
                j = next[j];
            }
        }
        for(int re: res)
            System.out.println(re);

    }

    static void getNext(){
        next[0] = -1;
        int m = s2.length;

        int k = -1;
        int j = 0;
        while(j < m - 1){// next[m - 1] 由 next[m - 2] 推出 所以 j < m - 1
            if(k == -1 || s2[k] == s2[j]){
                ++k;
                ++j;
                next[j] = k;
            }else{
                k = next[k];
            }
        }
    }

}

相關文章