String pattern matching algorithm --Java --KMP

package string;

import java.util.Scanner;

public class Kmp {

    /*
    * 求next数组
    * */
    private static int[] getNext(String s) {
        int []next = new int[s.length()];
        int i = 0;
        next[0] = -1;  //子串的第一个字符就不匹配
        int j = -1;
        while (i < s.length() - 1) {
            if (j == -1 || s.charAt(i) == s.charAt(j)) {
                i ++;
                j ++;
                next[i] = j;
            } else {
                j = next[j];
            }
        }
        return next;
    }
    /*
    * KMP算法
    * */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String sup = sc.nextLine();
        String sub = sc.nextLine();
        int []next = getNext(sub);
        int i = 0;
        int j = 0;
        while (j < sub.length() && i <sup.length()) {
            if(sub.charAt(j) == sup.charAt(i)) {
                i ++;
                j ++;
            } else {
                if (next[j] == -1) {
                    i ++;
                } else {
                    j = next[j];
                }
            }
        }
        if (j >= sub.length()) {
            System.out.println(sub + "在" + sup + "的第" + (i - j + 2) + "个字符处");
        } else {
            System.out.println(sup + "中未找到" + sub);
        }
    }
}

Published 57 original articles · won praise 55 · views 1947

Guess you like

Origin blog.csdn.net/qq_40561126/article/details/104300861