标签:== char bsp 算法 ati array turn [] int
public class KMP { public static void main(String[] args) { String str="ababxbababcadfdsss"; String subStr="abcad"; int[] next=getNext(subStr.toCharArray()); int p=kmp(next,str.toCharArray(),subStr.toCharArray()); System.out.println(p); } public static int[] getNext(char[] c) { int[] next=new int[c.length]; next[0]=0; for(int i=1,k=0;i<c.length;i++) { while(k>0&&c[k]!=c[i]) k=next[k-1]; if(c[k]==c[i]) k++; next[i]=k; } return next; } public static int kmp(int[] next,char[] str,char[] c) { for(int i=0,p=0;i<str.length;i++) { while(p>0&&str[i]!=c[p]) p=next[p-1]; if(str[i]==c[p]) p++; if(p==c.length) return i-c.length+1; } return -1; } }
标签:== char bsp 算法 ati array turn [] int
原文地址:http://www.cnblogs.com/mingyao123/p/7452701.html