KMP算法实现
依照KMP实现的算法,附带测试用例。
#include <algorithm>
#include<iostream>
#include<iterator>
#include <string>
#include <vector>
#include <cassert>
#include <cstring>
using namespace std;
/**计算next***/
void kmp_next(char *pattern,int *next)
{
int i = 0 ;
int j = next[0] = -1;
while(pattern[i]!= '\0')
{
if((j == -1) || (pattern[i] == pattern[j]))
next[++i]= ++j;
else
j = next[j];
}
}
/**计算next_val***/
void kmp_next_val(char *pattern,int *next_val)
{
int i = 0;
int j = next_val[0] = -1;
while(pattern[i]!='\0')
{
if((j == -1)|| (pattern[i] == pattern[j]))
if(pattern[++i] != pattern[++j])
next_val[i] = j;
else
next_val[i] = next_val[j];
else
j = next_val[j];
}
}
/****match 是长串**
*****pattern 是模式串**/
int kmp_match(char *match,char *pattern)
{
int m = strlen(pattern);
int next[m];
int i,j;
/**打印表格**/
for(i = 0; i < m ; ++i)
cout<<i<<'\t';
cout<<endl;
kmp_next(pattern,next);
copy(next,next+m,ostream_iterator<int > (cout,"\t"));
cout<<endl;
kmp_next_val(pattern,next);
copy(next,next+m,ostream_iterator<int > (cout,"\t"));
cout<<endl;
i = j = 0;
while((match[i]!='\0')&&(pattern[j]!='\0'))
{
if((j == -1)||(match[i] == pattern[j]))
++i,++j;
else
j = next[j];
}
return j == m?(i -j):-1;
}
int main(int argc,char *argv[])
{
char src[max_size];
char dst[max_size];
int m ,n;
int position = 0;
while(cin >> src >> dst)
{
position = kmp_match(src,dst);
if(position != -1)
cout<<"find at \t "<<position<<endl;
else
cout<<"not a substring\n";
cout<<"--------end----------\n\n";
}
return 0;
}
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 我在厂里搞 wine 的日子
· 如何通过向量化技术比较两段文本是否相似?
· 35+程序员的转型之路:经济寒冬中的希望与策略
· JavaScript中如何遍历对象?
· 领域模型应用
· 独立项目运营一周年经验分享
· 一款开源免费、通用的 WPF 主题控件包
· 独立开发,这条路可行吗?
· 【定时任务核心】究竟是谁在负责盯着时间,并在恰当时机触发任务?
· 解决了AI聊天的10个痛点后,我又做了一个新功能:交叉分析表