首页 技术 正文
技术 2022年11月14日
0 收藏 477 点赞 4,812 浏览 1647 个字

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

关于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的核心思想在于:通过部分匹配字符串的长度来决定待匹配字符串的移动长度,而不是每次只是移动一位。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,498
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,911
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,745
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,502
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,141
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,304