KMP算法详解

点击转到知乎KMP算法详解

我自己的java的实现代码

public static int kmp(char[] primary,char[] model,int position) {
		int i = position, j = 0;
		int[] next = next(model);
		if (i < primary.length && j < model.length) {
			if (primary[i] == model[j]) {
				i++;
				j++;
			} else {
				j = next[j];
			}
		}
		if (j == model.length) return i - j;
		else return 0;
	}
public static int[] pmt(char[] model) {
		int[] next = new int[model.length];
		next[0] = 0;
		int maxPosition = 0;
		for (int index = 1; index < next.length; index++) {
			maxPosition = next[index - 1];
			while (maxPosition > 0 && model[maxPosition] != model[index]) {
				maxPosition = next[maxPosition];
			}
			if (model[maxPosition] == model[index]) next[index] = maxPosition;
			else next[index] = 0;
		}
		return next;
	}
public static int[] next(char[] model) {
		int[] next = new int[model.length];
		next[0] = -1;
		int max = -1, index = 0;
		while (index < model.length - 1) {
			if (max == -1 || model[index] == model[max]) {
				max++;
				next[++index] = max;
			} else {
				max = next[max];
			}
		}
		return next;
	}
public static int[] nextval(char[] model) {
		int[] nextval = new int[model.length];
		nextval[0] = -1;
		int max = -1, index = 0;
		while (index < model.length - 1) {
			if (max == -1 || model[index] == model[max]) {
				max++;
				index++;
				if (model[index] == model[max]) {
					nextval[index] = nextval[max];
				} else {
					nextval[index] = max;
				}
			} else {
				max = nextval[max];
			}
		}
		return nextval;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值