数据结构——字符串-kmp算法

package com.it.alg.kmp;

import java.util.Arrays;
import java.util.stream.Collectors;

public class NextTest {
    public static void main(String[] args) {
        String s = "aaab";
        System.out.println(s);
        System.out.println(Arrays.stream(next(s)).boxed().collect(Collectors.toList()));
        System.out.println(Arrays.stream(nextVal(s)).boxed().collect(Collectors.toList()));
        System.out.println(kmp(s, "b"));
     }


    public static int[] next(String sub) {
        int[] next = new int[sub.length()];
        char[] chars = sub.toCharArray();
        int i = 0, j = -1;
        next[0] = -1;
        while (i < chars.length - 1) {
            if (j == -1 || chars[i] == chars[j]) {
                i++;
                j++;
                next[i] = j;
            } else {
                j = next[j];
            }
        }
        for (int item = 0; item < next.length; item++) {
            next[item]++;
        }
        return next;
    }

    public static int[] nextVal(String sub) {
        int[] nextVal = new int[sub.length()];
        char[] chars = sub.toCharArray();
        int i = 0, j = -1;
        nextVal[0] = -1;
        while (i < chars.length - 1) {
            if (j == -1 || chars[i] == chars[j]) {
                if (chars[++i] != chars[++j]) {
                    nextVal[i] = j;
                } else {
                    nextVal[i] = nextVal[j];
                }
            } else {
                j = nextVal[j];
            }
        }
        for (int item = 0; item < nextVal.length; item++) {
            nextVal[item]++;
        }
        return nextVal;
    }

    public static int kmp(String str, String sub) {
        char[] strChars = str.toCharArray();
        char[] subChars = sub.toCharArray();
        int[] nextVal = nextVal(sub);
        int i = 1, j = 1;
        while (i  <= str.length() && j <= sub.length()) {
            if (j == 0 || strChars[i - 1] == subChars[j - 1]) {
                i++;
                j++;
            } else {
                j = nextVal[j - 1];
            }
        }
        if (j > sub.length()) return i - sub.length() - 1;
        return -1;
    }
}

运行结果:
数据结构——字符串-kmp算法

上一篇:说说事务的概念,在JDBC编程中处理事务的步骤?


下一篇:python 数据清洗之提取字符串中的日期