kmp


class Solution{
	public static void main(String[] args) {
		String s1 = "abeababeabf";
		String s2 = "abeabf";
		System.out.println(KMP(s1,s2));

	}
	public static int KMP(String s1,String s2){
		if(s2.equals("")) return 0;
		char[] s = s1.toCharArray();
		char[] p = s2.toCharArray();
		int n = s.length;
		int m = p.length;
		int[] next = new int[m];
		for(int i = 1,j=0;i<m;i++){
			while(j>0 && p[i]!=p[j]) j = next[j-1];
			if(p[i] == p[j]) j++;
			next[i] = j;
		}
		for(int i=0,j=0;i<n;i++){
			while(j>0 && s[i]!=p[j]) j = next[j-1];
			if(s[i] == p[j]) j++;
			if(j == m) return i-m+1;
		}
		return -1;
	}
}
posted @ 2021-06-10 11:11  BOTAK  阅读(44)  评论(0编辑  收藏  举报