2019独角兽企业重金招聘Python工程师标准>>>
从头到尾彻底理解KMP
字符串匹配的KMP算法
KMP算法的Next数组详解
package leetcode;import java.util.Arrays;public class ImplementStrStr {public int strStr(String haystack, String needle) {if(haystack==null||needle==null)return -1;return haystack.indexOf(needle);}public int[] getNext(String str){int []preFix=new int[str.length()];int i=0;for(i=1;i<str.length();i++){int k=preFix[i-1];while(k!=0&&str.charAt(i)!=str.charAt(k))//从已经匹配过的字符串后缀在查找最大匹配k=preFix[k-1];if(str.charAt(i)==str.charAt(k)){k++;preFix[i]=k;}else{preFix[i]=0;}}return preFix;}public int indexOf(String haystack,String needle){int heyLength=haystack.length();int needLength=needle.length();int i=0;int j=0;while(i<heyLength&&j<needLength){if(haystack.charAt(i)==needle.charAt(j)){i++;j++;}else{i=i+1-j;j=0;}}if(j==needLength){return i-j;}else{return -1;}}public int indexOf2(String haystack,String needle){int heyLength=haystack.length();int needLength=needle.length();if(needLength==0){return 0;}int i=0;int j=0;int pre[]=getNext(needle);while(i<heyLength&&j<needLength){while(j>0&&haystack.charAt(i)!=needle.charAt(j)){j = pre[j-1];}if(haystack.charAt(i)==needle.charAt(j)){j++;}i++;if(j==needLength){return i-j;}}return -1;}public int[] next(String param){int[] next=new int[param.length()];next[0]=-1;int length=param.length();int i=0;int j=-1;while(i<length-1){if(j==-1||param.charAt(i)==param.charAt(j)){next[++i]=++j;}else{j=next[j];}}return next;}public int kmp(String str,String param){if(null==str||null==param){return -1;} int[] next=next(param);int strLength=str.length();int paramLength=param.length();int i=0;int j=0;while(i<strLength&&j<paramLength){if(j==-1||str.charAt(i)==param.charAt(j)){i++;j++;}else{j=next[j];}}if(j==paramLength){return i-j;}else{return -1;}}public static void main(String[] args) {ImplementStrStr i=new ImplementStrStr();System.out.println(i.indexOf2("abc", ""));System.out.println(i.indexOf2("a", "a"));
// System.out.println(i.indexOf2("mississippi","pi"));System.out.println(i.indexOf2("abbababbabbbabaaab","abbabbbabaa"));//System.out.println(i.kmp("abc", ""));System.out.println(i.kmp("a", "a"));
// System.out.println(i.indexOf2("mississippi","pi"));System.out.println(i.kmp("abbababbabbbabaaab","abbabbbabaa"));System.out.println(Arrays.toString(i.getNext("issip")));}
}