KMP字符串匹配算法

2014-11-24 08:49:18 · 作者: · 浏览: 0
public class KMP {
	static int[] next;
	/**
	 * 
	 * @param t  模式串,求得模式串回溯的next函数
	 */
	static void next(String t) {
		next = new int[t.length()];
		next[0] = -1;
		int j = -1;
		int i = 0;
		while (i < t.length()-1) {
			if (j == -1 || t.charAt(i) == t.charAt(j)) {
				i++;
				j++;
				if(t.charAt(i) == t.charAt(j)){
					next[i] = next[j];
				}else{
					next[i] = j;
				}
			}else{
				j = next[j];
			}
		}
	}
	/**
	 * 
	 * @param s 主串
	 * @param t 模式串
	 * @param pos 从主串的pos下标位置开始匹配
	 */
	static int match(String s,String t,int pos){
		int i=pos;
		int j=0;
		while(i
t.length()-1){ return i-j; }else{ return -1; } } public static void main(String[] args) { String s = "aaaasad"; String t = "sa"; next(t); System.out.println(match(s,t,0)); } }