KMP算法中较为典型的就是字符串匹配算法。“给定两个字符串,主串和模式串。返回主串中模式串第一次出现的位置,未出现返回-1,模式串为空返回0”。暴力求解也可以求得该问题,即主串与模式串进行匹配,如果不成功,主串的起始位置+1,如这样一个例子
显然这样效率是不高的,为O(m*n)。我们应将其每一次回溯到一个合适的位置来提高其效率
如图上这样就能将效率提升至O(m+n),此处重点在于模式串的回溯。可以设计一个回溯数组来记录每次回溯的位置,当主串与模式串不匹配时,就将模式串的指针回溯到next[i]位置,而主串不需要回溯,这大大降低了时间复杂度。其核心是模式串的回溯数组next[],即当主串与模式串不匹配时,主串当前位置需要匹配模式串的哪个位置。下面代码则是演示了如何实现next数组。
//目的是求得next数组
public void getNext(String str,int[] next){
//数组的长度是比模式串的长度长1
int strLength = str.length();
//当模式串在第一个字符处未能匹配,而模式串已经是第一个字符了,不能再回溯了,因此主串需要向后移动一位,用0表示主串向后移动一位
next[1] = 0;
//表示指针当前位置
int now = 1;
//指针回溯的位置,0表示不回溯模式串,主串向下一位
int nex = 0;
while(now < strLength){
//在设置next数组时,需要判断本字符是否和它回溯的位置的字符匹配,是则下一个字符的nex + 1
if(nex == 0 || str.charAt(now - 1) == str.charAt(nex - 1)){
//等价于++now; ++nex; next[now] = nex;
next[++now] = ++nex;
}else{
//如果本字符和它回溯的位置的字符不匹配,则回溯字符至nex位置,进行上面的判断,如果符合则使用回溯过的nex + 1,否则重复此过程;
nex = next[nex];
}
}
}
/* 例 举一个模式串next数组的例子
* 1 2 3 4 5 6 7 8 next数组下标,这里数组的下标从1开始
* a b a c a b a d 模式串
* 0 1 1 2 1 2 3 4 next数组,表示不匹配时,模式串回溯的位置
*/
完整代码
class Solution {
public int strStr(String haystack, String needle) {
if(needle == ""){
return 0;
}
int m = haystack.length();
int n = needle.length();
int[] dp = new int[n + 1];
getNext(needle,dp);
int i = 0,j = 1;
while(i < m){
if(haystack.charAt(i) == needle.charAt(j - 1)){
if(j == n){
return i - j + 1;
}
++i;
++j;
}else{
j = dp[j];
if(j == 0){
i++;
j++;
}
}
}
return -1;
}
public void getNext(String str,int[] next){
int strLength = str.length();
next[1] = 0;
int now = 1;
int nex = 0;
while(now < strLength){
if(nex == 0 || str.charAt(now - 1) == str.charAt(nex - 1)){
next[++now] = ++nex;
}else{
nex = next[nex];
}
}
}
}