模式匹配(Pattern Matching) 即子串定位运算(Index函数)。
如果之前还不是特别了解KMP算法的整体思想,可以看这篇文章的讲解
图解字符串匹配的KMP算法
这里重点介绍下KMP的算法实现
next数组的含义
next[j]=K表示在串p0p1p····pj-1中有相等的前缀子串p0p1p2······pk和后缀子串pj-k-1pj-k········pj-1,这个查找过程其实也是一个模式匹配过程,只不过目标串和模式串是同一个串。
如何求next[j+1]
设已知next[j]=k,则有p0p1····pk=pj-1-1pj-1·····pj-1
1、若pk+1=pj ,next[j+1]=next[j]+1;
2、若pk+1!=pj
这时就要从已知条件入手,已知p0p1····pk=pj-1-1pj-1·····pj-1,
现在从p0p1····pk中找到一个下标h,使得p0p1·····ph=pk-h-1pk-h·····pk
又因为 pk-h-1pk-h·····pk=pj-h-1pj-h·····pj-1
所以 p0p1·····ph=pk-h-1pk-h·····pk=pj-h-1pj-h·····pj-1
现在如果ph+1=p[j],那么 next[j]=next[h]+1
如果ph+1!=p[j],那么继续在p0p1·····ph=pk-h-1pk-h继续上述的步骤缩小范围,直到next[t]=-1,才算失败,这时next[k]=-1
字符串匹配思想
用模式串从匹配串头开始,逐渐匹配,若遇到第一个p[i]!=m[j]时,说明前i-1个字符已经与主串匹配,利用这个已知信息将模式串p向右移动next[i]个位置,继续向下进行匹配比较
#include<iostream>
#include<string>
using namespace std;
int* get_next(const string &s)
{
int len = s.size();
int *next = new int[len];
int i = -1, j = 0;//j始终在i的右边
next[0] = -1;
while (j < len)
{
if (i == -1 || s[i] == s[j])
{
i++;
j++;
next[j] = i;
}
else i = next[i];
}
return next;
}
int match(int *next, const string &pat, const string &mat)
{
int p_size = pat.size();
int m_size = mat.size();
int i = 0, j = 0;
while (i < p_size&&j < m_size)
{
if (i == -1||pat[i] == mat[j] )
{
i++;
j++;
}
else i = next[i];
}
if (i < p_size) return -1;
else return j - p_size;
}
int main()
{
string pat, mat;//pat为 模式串,mat为匹配串
cin >> mat >> pat;
int len = pat.size();
int *next = new int[len];
next = get_next(pat);
int pos = match(next, pat, mat);
cout << pos << endl;
getchar();
getchar();
}