标签:int span Stub AC pattern har kmp算法 col stat
KMP算法
1 package cn.wubowei; 2 3 public class KPM { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 String pattern="ABABCABAA"; 8 char[] patternch=pattern.toCharArray(); 9 char[] text="ABABABABCABAAABAB".toCharArray(); 10 int n= pattern.length(); 11 int[] prefix=new int[n]; 12 // prefixtable(patternch, prefix, n); 13 // movePrefixTable(prefix, n); 14 kmpsearch(text, patternch); 15 16 } 17 public static void prefixtable (char pattern[], int prefix[], int n) { 18 prefix[0]=0; 19 int len=0; 20 int i=1; 21 while (i<n) { 22 if(pattern[i] == pattern[len]) { 23 len++; 24 prefix[i]=len; 25 i++; 26 }else { 27 if(len>0) { 28 len =prefix[len-1]; 29 }else { 30 prefix[i]= len; 31 i++; 32 } 33 } 34 } 35 } 36 37 public static void movePrefixTable(int prefix[], int n) { 38 // int i=0; 39 for(int i=n-1;i>0;i--) { 40 prefix[i]=prefix[i-1]; 41 } 42 prefix[0]=-1; 43 } 44 45 public static void kmpsearch (char text[], char pattern[]) { 46 int n= pattern.length; 47 int m=text.length; 48 int[] prefix=new int[n]; 49 prefixtable(pattern, prefix, n); 50 movePrefixTable(prefix,n); 51 int i=0; 52 int j=0; 53 54 while(i<m) { 55 if(j==n-1&&text[i]==pattern[j]) { 56 System.out.println(i-j); 57 j=prefix[j]; 58 } 59 if(text[i]== pattern[j]) { 60 i++; 61 j++; 62 }else { 63 j=prefix[j]; 64 if(j==-1) { 65 i++;j++; 66 } 67 68 } 69 } 70 } 71 72 }
标签:int span Stub AC pattern har kmp算法 col stat
原文地址:https://www.cnblogs.com/ncznx/p/9175714.html