模式匹配之Kmp算法

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;
	}
}

  运行效果:

posted @ 2015-01-26 16:07  UDLD  阅读(188)  评论(0编辑  收藏  举报