Java教程

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

本文主要是介绍数据结构——字符串-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算法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!