0318 KMP

最终还是选择用java而不是python,其实没有什么难不难,当初学个乘法口诀也是很难,人总是要不断进取的。
希望在美国找工作顺利

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

一、基础知识

二、code

package basic_class_02;

public class Code_01_KMP {

    public static int getIndexOf(String s, String m) {
    	if (s == null || m == null || m.length() < 1 || s.length() < m.length()) {
    		return -1;
    	}
    	char[] ss = s.toCharArray();
    	char[] ms = m.toCharArray();
    	int si = 0;
    	int mi = 0;
    	int[] next = getNextArray(ms);
    	while (si < ss.length && mi < ms.length) {
    		if (ss[si] == ms[mi]) {
    			si++;
    			mi++;
    		} else if (next[mi] == -1) {
    			si++;//str2已经到了第一个了还是匹配不上,开头不行,你str1就++吧
    		} else {
    			mi = next[mi];//就是说str2还可以跳
    		}
    	}
    	return mi == ms.length ? si - mi : -1;
    }
    
    public static int[] getNextArray(char[] ms) {
    	if (ms.length == 1) {
    		return new int[] { -1 };
    	}
    	int[] next = new int[ms.length];
    	next[0] = -1;
    	next[1] = 0;
    	int pos = 2;//后面减一了,长度   位置
    	int cn = 0;
    	while (pos < next.length) {
    		if (ms[pos - 1] == ms[cn]) {
    		//表示长度+1
    			next[pos++] = ++cn;  //next k=k
    		//cn跳到的位置跟前一个不等,两种情况  可以往前跳  或者到了最左边了
    		} else if (cn > 0) {//我还可以往前跳  
    			cn = next[cn];//next数组的值就是我要跳的位置
    		} else {
    		//跳到最左了,当前位置的最长前缀和最长后缀是0
    			next[pos++] = 0;
    		}
    	}
    	return next;
    }
    
    public static void main(String[] args) {
    	String str = "abcabcababaccc";
    	String match = "ababa";
    	System.out.println(getIndexOf(str, match));
    
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值