代码:
/**
* next数组记录前缀和后缀的公共长度
* @param s
*/
public int[] get_next(String s){
int[] next = new int[s.length()];
for(int i = 1,j = 0; i < s.length(); i++){
while (j > 0 && s.charAt(j) != s.charAt(i))
j = next[j - 1];
if(s.charAt(j) == s.charAt(i))
next[i] = ++j;
}
return next;
}
/**
* 利用KMP算法
* @param s1
* @param s2
* @return
*/
public void find(String s1, String s2){
int ans = 0;
int[] next = get_next(s2);
for(int i = 0, j = 0; i < s1.length();){
if(s1.charAt(i) == s2.charAt(j)){
i++;
j++;
if(j != s2.length()) continue;
else {
ans = i - s2.length();
System.out.print(ans);
}
}
/**
* 到这里有两种情况:
* 一是完全匹配成功了
* 二是匹配失败了
* 两种情况是一样的
*/
if(j > 0)
j = next[j - 1];
else if(s1.charAt(i) != s2.charAt(j))
i++;
}
}
leetcode: 28
b站:
KMP字符串匹配算法1
KMP字符串匹配算法2
参考:字符串匹配的KMP算法