面试常规算法复习kmp

送分小仙女□ 提交于 2019-12-06 14:34:06

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");
    }

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!