leetCode的28题与KMP算法相关,此篇根据其官方解析精简
目标:求前缀pi(i)
pi(i):在下标为i以及以前的字符构成的字符串中最长相等的前后字符串的长度;
前缀函数的两个特性:
pi(i)<=pi(i-1)+1;
s[i]=s(pi(i-1))时,pi(i)=pi(i-1)+1;
最长前后缀: 前s[pi(i-1)-j:pi(i-1)-1] 后s[i-pi(i-1):i-1]
引入一个变量j
使j最大且满足条件,则:
在算法中,设定j+1=pi(i),初始j=pi(i-1),
前s[0:j-1] 后s[i-j:i-1]
s(i)=s(j)--> pi(i)=j+1 //成功
只要不断迭代j,使得j=pi(j-1),让是s(i)=s(j)或j=0即可
public int strStr(String haystack, String needle) {
int n = haystack.length(), m = needle.length();
if (m == 0) {
return 0;=
}
int[] pi = new int[m];
for (int i = 1, j = 0; i < m; i++) {
while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
j = pi[j - 1];
}
if (needle.charAt(i) == needle.charAt(j)) {
j++;
}
pi[i] = j;
}
for (int i = 0, j = 0; i < n; i++) {
while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
j = pi[j - 1];
}
if (haystack.charAt(i) == needle.charAt(j)) {
j++;
}
if (j == m) {
return i - m + 1;
}
}
return -1;
}