字符串匹配算法之————KMP算法

时间:2023-03-08 21:36:41
字符串匹配算法之————KMP算法

上一篇中讲到暴力法字符串匹配算法,但是暴力法明显存在这样一个问题:一次只移动一个字符。但实际上,针对不同的匹配情况,每次移动的间隔可以更大,没有必要每次只是移动一位:

关于KMP算法的描述,推荐一篇博客:https://blog.csdn.net/weixin_36604953/article/details/78576637

该博客详细的描述了KMP算法原理。下面的代码实现了KMP算法:

 //使用暴力穷举法, KMP算法完成字符串匹配算法
# include "iostream"
#include"string"
#include"vector"
using namespace std;
vector<int>& BFmatch(string & , string & , vector<int>&);
vector<int>& KMPStrMatch(string &, string &, vector<int>&);
void ShowPos(vector<int>& );
int main()
{
string ModelStr, SonStr;
vector<int> pos;
cout << "请输入待匹配字符串:";
cin >> ModelStr ;
cout << endl;
cout << "请输入子字符串:";
cin >> SonStr;
cout << endl;
//BFmatch(ModelStr, SonStr, pos);
KMPStrMatch(ModelStr, SonStr, pos);
ShowPos(pos);
system("pause");
}
vector<int>& BFmatch(string & ModelStr, string & SonStr,vector<int>& pos)
{
for (int i = ; i < ModelStr.size(); i++)
{
int k = ;
for (int j = i; k < SonStr.size(); j++, k++)
{
if (SonStr[k] == ModelStr[j])
continue;
else
break;
}
if (k == SonStr.size())
pos.push_back(i);
}
return pos;
}
void ShowPos(vector<int>& pos)
{
if (pos.size() != )
{
cout << "the first position of MatchingStr:";
for (int i = ; i < pos.size(); i++)
{
cout << pos[i] << "\t";
}
cout << endl;
}
else
cout << "no such string!" << endl;
}
vector<int>& KMPStrMatch(string & ModelStr, string & SonStr, vector<int>& pos)
{
string ComStr;
string tmp1, tmp2;
int j = , i = , len = ;;
while(j< (ModelStr.size()- SonStr.size()+))
{
if (ModelStr[j] != SonStr[])
{
j++;
continue;//首位不匹配直接加1
}
else
{
while ((j< ModelStr.size())&&(ModelStr[j] == SonStr[i]))//&&前面的约束条件保证了不会发生内存越界
{
j++;
i++;
}
if (i == SonStr.size())
pos.push_back(j - SonStr.size());
j = j - i;
ComStr = SonStr.substr(, i - );
for (int q = ; q < ComStr.size(); q++)
{
tmp1=ComStr.substr(q, ComStr.size() - );
tmp2=ComStr.substr(, ComStr.size() - - q);
if (tmp1 == tmp2)
len++;
}
j = j + i-len;
i = ;
len = ;
}
}
return pos;
}

总之,KMP的核心思想在于:通过部分匹配字符串的长度来决定待匹配字符串的移动长度,而不是每次只是移动一位。