KMP算法的学习笔记
一、KMP的理论基础
1.解决了什么问题:
2. 前缀 与 后缀
3. 最长相等的前后缀
4. 如何利用 前缀表 进行匹配
二、KMP算法的代码实现
1. 获取next数组
2. 利用next数组进行匹配
3. 学以致用
力扣-28.实现strStr()
class Solution {
public:
// 获得next数组
void getNext(string needle, int* next)
{
//初始化:
int j = -1;
next[0] = j;
//遍历模板串
for(int i = 1; i<needle.size(); i++) //注意这里的i是从1开始的,因为next[0]已经被初始化为-1了
{
//处理前后缀不相同的情况:
while(j>=0 && needle[i] != needle[j+1]) //注意这里用while,因为如果前后缀一直不相等要连续跳转。
{
j = next[j]; //j 回退
}
//处理前后缀相等的情况
if(needle[i] == needle[j+1])
{
j++;
}
next[i] = j;
}
}
//利用next数组进行匹配
int getPosition(string haystack, string needle, int* next)
{
int j = -1;
for(int i = 0; i<haystack.size(); i++)
{
//处理冲突位置:
while(j>=0 && haystack[i] != needle[j+1])
{
j = next[j]; //如果发生匹配冲突,j回退
}
//处理匹配成功
if( haystack[i] == needle[j+1])
{
j++; //如果匹配成功,那么i和j一起前移动,注意,i的移动体现在for循环里面
}
//判断文本串中存在模板串
if(j == needle.size() - 1)
{
return (i - needle.size() + 1); //返回文本串中模板串存在的第一个位置
}
}
return -1; //如果模板串匹配失败,返回-1
}
int strStr(string haystack, string needle) {
//处理特殊情况:
if(haystack.size() == 0 && needle.size() == 0) return 0;
if(haystack.size() != 0 && needle.size() == 0) return 0;
if(haystack.size() == 0 && needle.size() != 0) return -1;
//定义next数组
int next[needle.size()];
//获取next数组
getNext(needle, next);
//获取匹配位置
return getPosition(haystack, needle, next);
}
};
4. 参考学习
代码随想录