面试常规算法复习kmp

1.核心是求next数组
2.考虑两种情况:
-当p[j] == p[k]时,当前的next等于上一个next加一
-当p[j] != p[k]时

package com.company;

import java.util.Scanner;

public class kmp {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str1 = in.next();
        String str2 = in.next();
        int[] next = getNext(str2.toCharArray());
        getkmp(str1.toCharArray(), str2.toCharArray(), next);
    }

    public static int[] getNext(char str[]){
        int[] next = new int[1005];
        int n = str.length;
        next[0] = -1;
        int k = -1;
        int j = 0;
        while (j < n){
            if (k == -1 || str[k] == str[j]){
                k++;
                j++;
                next[j] = k;
            }
            else{
                k = next[k];
            }
        }
        for(int i = 0; i < n; i++){
            System.out.printf("%d ", next[i]);
        }
        System.out.println();
        return next;
    }

    public static void getkmp(char str1[], char str2[], int next[]){
        int len1 = str1.length;
        int len2 = str2.length;
        int i = -1;
        int j = -1;
        while(i < len1 && j < len2){
            if (j == -1 || str1[i] == str2[j]){
                i++;
                j++;
            }
            else {
                j = next[j];
            }
            System.out.printf("%d, %d\n", i, j);
        }
        if (j == len2) System.out.println(i-j);
        else System.out.println("no");
    }

}

猜你喜欢

转载自www.cnblogs.com/liuqiyu/p/11990258.html