有一个文本串S和一个模式串P,要查找P在S中的位置——KMP算法

关键是求解NEXT数组  Next数组就是当前字符之前的字符串中,有多大长度的相同前缀与后缀

public class KMP {
  /**
   * KMP算法的实现
   */
	/**
	 * 求解NEXT数组
	 */
	private  static void getNext(char [] p,int [] next){
		int len = p.length;
		next[0]= -1;
		int k = -1;
		int j =0;
		while(j<len-1){
			if(k==-1 || p[j]==p[k]){
				++j;
				++k;
				if(p[j]!=p[k]){
					next[j] =k;
				}else{
					next[j]=next[k];
				}
			}else{
				k=next[k];
			}
		}
	}
	
	public static int KmpSearch(char [] s,char [] p){
		int i=0;
		int j =0;
		int [] next = new int[p.length];
		getNext(p, next);
		int SLen = s.length;
		int PLen = p.length;
		while(i<SLen && j<PLen){
			if(j ==-1|| s[i] == p[j]){
				i++;
				j++;
			}else{
				j = next[j];
			}
		}
		if( j ==PLen){
			return i-j;
		}else{
			return -1;
		}
	}
	public static void main(String[] args) {
		int index = KmpSearch("ADBDGSDFGSD".toCharArray(), "DGS".toCharArray());
		System.out.println(index);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_39536716/article/details/83047210