1. 首先将pattern_str模式串预处理,生成next数组
2. 进入主循环,遍历query字符串的每一个字符
2.1. 比较query和pattern_str的字符
2.2. 当发现不匹配字符时,查询next数组,得到匹配前缀所对应的最长可匹配前缀子串,移动pattern_str到对应位置
2.3.if 当前字符匹配,则继续循环
next数组是指pat到当前字符之前(去除当前字符)的字符串的最大公共前缀后缀长度。
class Solution {
public:
void getNext(vector<int>& next, const string& s) {
int j = -1;
next[0] = j;
for(int i = 1; i < s.size(); i++) { // 注意i从1开始
while (j >= 0 && s[i] != s[j + 1]) { // 前后缀不相同了
j = next[j]; // 向前回溯
}
if (s[i] == s[j + 1]) { // 找到相同的前后缀
j++;
}
next[i] = j; // 将j(前缀的长度)赋给next[i]
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0) {
return 0;
}
vector<int> next(needle.size());
getNext(next, needle);
int j = -1; // // 因为next数组里记录的起始位置为-1
for (int i = 0; i < haystack.size(); i++) { // 注意i就从0开始
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) ) { // 文本串s里出现了模式串t
return (i - needle.size() + 1);
}
}
return -1;
}
}
// 实现二:
void get_next(const string& pattern_str, vector<int> & next)
{
int j = 0;
for (int i = 2; i < pattern_str.length(); i++)
{
while (j != 0 and (pattern_str[j] != pattern_str[i - 1]))
{
j = next[j];
}
if (pattern_str[j] == pattern_str[i - 1])
{
j++;
}
next[i] = j;
}
}
int KMP(const string & query, const string & pattern_str)
{
vector<int> next(pattern_str.length(), 0);
get_next(pattern_str, next);
int j = 0;
for (int i = 0; i < query.length(); i++)
{
while (j > 0 and (pattern_str[j] != query[i]))
{
j = next[j];
}
if (pattern_str[j] == query[i])
{
j++;
}
if (j == pattern_str.length())
{
cout << "start_pos is " << i - pattern_str.length() + 1 << endl;
return i - pattern_str.length() + 1;
}
}
return -1;
}
int main() {
cout << "hahaha" << endl;
string query = "ATGTGAGCTGGTGTGTGCFAA";
string pattern_str = "GTGTGCF";
int a = KMP(query, pattern_str);
cout << a << endl;
return 0;
}