Kmp:
算法定义借鉴wikipedia:
http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm#KMP_algorithm
代码:
import java.util.Scanner; public class Main { public static void main(String[] argv){ Main u = new Main(); Scanner in = new Scanner(System.in); String t = in.nextLine(); String s = in.nextLine(); int[] next = new int[s.length()]; char [] n = t.toCharArray(); char [] m = s.toCharArray(); next = u.check(m); for(int i=0; i<next.length; i++){ System.out.print(next[i]); } System.out.println(); int k=0; int num=0; for(int i=0; i<t.length();i++){ if(n[i]==m[k]) { k++; if(k==m.length) {num++;k=next[k-1];} } else k=next[k]; } System.out.println(num); } public int[] check(char [] t){ int next[] = new int [t.length]; next[0]=0; int j=1; while(j<t.length){ int k=next[j-1]; while (t[j]!=t[k]&&k!=0) k=next[k-1]; if(t[j]==t[k]) next[j]=k+1; else next[j]=0; // System.out.println(" "+next[j]); j++; } return next; } }
运行效果:
时间: 2024-10-12 22:36:28