关于KMP算法,可以先看这篇博客,图文并茂,不过里面的算法不对,不值得借鉴,https://www.cnblogs.com/dusf/p/kmp.html
给你一个文本串 T ,一个非空模板串 S ,问 T 在 S 中出现了多少次
数据范围:1 \le len(S) \le 500000, 1 \le len(T) \le 10000001≤len(S)≤500000,1≤len(T)≤1000000
要求:空间复杂度 O(len(S))O(len(S)),时间复杂度 O(len(S)+len(T))O(len(S)+len(T))
输入:“ababab”,“abababab”
输出:2
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 计算模板串S在文本串T中出现了多少次
* @param S string字符串 模板串
* @param T string字符串 文本串
* @return int整型
*/
public int kmp (String S, String T) {
// write code here
if("".equals(S) || S == null || "".equals(T) || T == null){
return 0;
}
int next[] = getNext(S);
int i = 0;
int j = 0;
int SL = S.length();
int output = 0;
char sChar[] = S.toCharArray();
char tChar[] = T.toCharArray();
int TL = T.length();
while(i < TL){
//j回到了-1,说明sChar[SL - 1] != sChar[0] != tChar[i]
if(j == -1 || sChar[j] == tChar[i]){
i++;
j++;
}else{
j = next[j];
}
if(j == SL){
output++;
j = next[j];
}
}
return output;
}
public int[] getNext(String S){
char str[] = S.toCharArray();
int next[] = new int[S.length() + 1];
next[0] = -1;
next[1] = 0;
int cur = 2;
int k = 0;
while(cur <= S.length()){
if(k == -1 || str[cur - 1] == str[k]){
next[cur++] = ++k;
}else{
k = next[k];
}
}
return next;
}
}