28.找出字符串中第一个匹配项的下标
KMP算法:
1.next数组如何得来
2.如何使用next数组进行最快捷的匹配
关键点:
在计算next数组时,循环中的i和j代表什么
i代表后缀末尾的下标 j代表前缀末尾的下标
示例:
h: aafaab n: aab
确定next数组
n : aab
i = 1 j = 0 n[i] == n[j] j++ n[i] = n[1] = j = 1 i++
i = 2 j = 1 n[i] != n[j] j = n[j - 1] = n[0] = 0 n[i] = n[2] = j = 0 i++
i = 3 跳出循环
n[] = [0,1,0]
a a
aa aa
aaf aab -> aafa a
aafaa aa
aafaab aab 匹配成功
class Solution {
public int strStr(String haystack, String needle) {
if(needle.length() == 0) return 0;
int[] next = new int[needle.length()];
getnext(needle,next);
int j = 0;
// 如何使用next数组进行最快捷的匹配
for(int i = 0; i < haystack.length(); i++){
while(j > 0 && haystack.charAt(i) != needle.charAt(j)){
j = next[j - 1];
}
if(haystack.charAt(i) == needle.charAt(j)){
j++;
}
if(j == needle.length()){
return i - needle.length() + 1;
}
}
return -1;
}
public void getnext(String needle,int[] next){
int j = 0;
next[0] = 0;
// next数组如何得到
for(int i = 1; i < needle.length(); i++){
while(j > 0 && needle.charAt(i) != needle.charAt(j)){
j = next[j - 1];
}
if(needle.charAt(i) == needle.charAt(j)){
j++;
}
next[i] = j;
}
}
}