public class kmp{
	static int KMP(String S,String T, int pos){
		if(S.length() < T.length()){
			return -1;
		}		
		char[] s = new char[S.length()];
		char[] t = new char[T.length()];
		for(int k = 0; k < S.length(); k++){
			s[k] = S.charAt(k);
		}
		for(int k = 0; k < T.length(); k++){
			t[k] = T.charAt(k);
		}
		int[] next = new int[T.length()];
		GetNextArray(T, next);
		int i, j;
		for(i = pos, j = 0; i < S.length() && j < T.length(); ){
			if(-1 == j || s[i] == t[j]){
				++i;
				++j;
			}else{
				j = next[j];
			}
		}
		if(j >= T.length()){
			return i - T.length();
		}else{
			return -1;
		}
	}

	 static void  GetNextArray(String str, int next[]){
		char[] s = new char[str.length()];
		for(int k = 0; k < str.length(); k++){
			s[k] = str.charAt(k);
		}
		next[0] = -1;
		for(int i = 0, j = -1; i < str.length() - 1; ){
			if(-1 == j ||
				s[i] == s[j]){
				++i;
				++j;
				next[i] = j;
			}else{
				j = next[j];
			}
		}
	}
}


 

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐