KMP模式匹配的java实现

import java.util.Scanner;
    public class Main {
        public static void main(String[] args) {
            try (Scanner s = new Scanner(System.in)) {
                String t = s.nextLine();
                String p = s.nextLine();
                solveMethod(t, p);
            }
        }
        private static void solveMethod(String t, String p) {
            int[] lps = computeLPS(p);
            int i = 0, j = 0;
            while (i < t.length()) {
                if (t.charAt(i) == p.charAt(j)) {
                    i++;
                    j++;
                }
                if (j == p.length()) {
                    System.out.println(i - j + 1);
                    return;
                } else if (i < t.length() && t.charAt(i) != p.charAt(j)) {
                    if (j != 0) {
                        j = lps[j - 1];
                    } else {
                        i++;
                    }
                }
            }
            System.out.println("No");
        }
        private static int[] computeLPS(String p) {
            int[] lps = new int[p.length()];
            int len = 0, i = 1;
            while (i < p.length()) {
                if (p.charAt(i) == p.charAt(len)) {
                    len++;
                    lps[i] = len;
                    i++;
                } else {
                    if (len != 0) {
                        len = lps[len - 1];
                    } else {
                        lps[i] = 0;
                        i++;
                    }
                }
            }
            return lps;
        }
    }

 

你可能感兴趣的:(code,java,算法,开发语言)