今天学习了一下KMP算法,并没有想象中难,上午看的算法,晚上依旧能根据理解写出来代码,所以还是需要多动手~~
题目链接
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 计算模板串S在文本串T中出现了多少次
* @param S string字符串 模板串
* @param T string字符串 文本串
* @return int整型
*/
public static void getNext(String w, int[] next) {
//next[i]表示字串0-i中最长前后缀的前缀的末尾位置
next[0]=-1;//前后串不能为本串
int j=next[0];
for(int i=1;i<w.length();i++) {
while(j!=-1&&w.charAt(i)!=w.charAt(j+1)) {
j=next[j];
}
if(w.charAt(i)==w.charAt(j+1)) {
j++;
}
next[i]=j;
}
}
public int kmp (String S, String T) {
// write code here
int[] next=new int[S.length()];
getNext(S,next);
int cnt=0;
//KMP
int j=-1;
for(int i=0;i<T.length();i++) {
while(j!=-1&&T.charAt(i)!=S.charAt(j+1)) {
j=next[j];
}
if(T.charAt(i)==S.charAt(j+1)) {
j++;
}
if(j==S.length()-1) {
cnt++;
j=next[j];
}
}
return cnt;
}
}