KMP

KMP

import java.util.Scanner;

class Solution {

    private static int[] getNext(char[] str) {
        int[] next = new int[str.length];
        int i = 0, j = -1;
        next[0] = -1;
        while (i < str.length - 1) {
            if (j == -1 || str[i] == str[j]) {
                ++i;
                ++j;
                if (str[i] == str[j]) {
                    next[i] = next[j];
                } else {
                    next[i] = j;
                }
            } else {
                j = next[j];
            }
        }
        return next;
    }

    private static int match(String haystack, String needle) {
        if ("".equals(needle)) {
            return 0;
        }
        char[] str1 = haystack.toCharArray();
        char[] str2 = needle.toCharArray();

        int[] next = getNext(str2);

        int index1 = 0, index2 = 0;

        while (index1 < str1.length && index2 < str2.length) {
            if (index2 == -1 || str1[index1] == str2[index2]) {
                ++index1;
                ++index2;
            } else {
                index2 = next[index2];
            }
        }

        return index2 == str2.length ? index1 - index2 : -1;
    }


    public static int strStr(String haystack, String needle) {
        return match(haystack, needle);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            System.out.println(strStr(in.next(), in.next()));
        }
    }
}
posted @ 2021-10-12 10:03  Tianyiya  阅读(24)  评论(0)    收藏  举报