KMP算法
来源:互联网 发布:壹卡会可以在淘宝用吗 编辑:程序博客网 时间:2024/05/19 03:27
KMP算法
#include <iostream>#include <vector>
#include <string>
using namespace std;
const int INF=0x7fff;
int p[INF];
//ababacb
//
void findB(string str)
{
int len=str.length();
string strcopy(len+1,0);
strcopy[0]='0';
for (int i=0;i<len;i++)
{
strcopy[i+1]=str[i];
}
p[0]=0;
p[1]=0;
for (int i=2;i<=len;i++)
{
int k=i-1;
while(strcopy[i]!=strcopy[p[k]+1])
{
k=p[p[k]];
if (k==0)
{
break;
}
}
if (k==0)
{
p[i]=0;
}
else
{
p[i]=p[k]+1;
}
}
cout<<strcopy<<endl;
for (int i=1;i<=len;i++)
{
cout<<p[i]<<endl;
}
}
//string strb="ababacb";
//string stra="abababaabab";
int KMP(string strb,string stra)
{
int lena=stra.length();
int lenb=strb.length();
string strcb(lenb+2,'x');
string strca(lena+2,'x');
for (int i=0;i<lena;i++)
{
strca[i+1]=stra[i];
}
for (int i=0;i<lenb;i++)
{
strcb[i+1]=strb[i];
}
int i=1,j=1;
bool flag=false;
int index=0;
cout<<strca<<endl;
cout<<strcb<<endl;
bool flag1=true;
for(i=1;i<=lena&&flag1;)
{
while (strca[i]==strcb[j]&&j<=lenb)
{
i++;
j++;
if (i>lena)
{
flag1=false;
break;
}
}
if (j>lenb)
{
flag=true;
index=i-j+1;
break;
}
i--;
j--;
j=p[j];
if (j==0)
{
i++;
while(strca[i]!=strcb[1]&&flag1)
{
i++;
if (i>lena)
{
flag1=false;
break;
}
}
j=1;
}
}
return index;
}
int main()
{
string strb="ababacb";
string stra="abababaababacb";
string testb="abdbay";
string testa="ddabdddabdbac";
findB(testb);
int x=KMP(testb,testa);
cout<<x<<endl;
}
0 0
- KMP算法详解 【KMP】
- 【KMP】KMP算法模板
- KMP hihoCoder1015 KMP算法
- kmp算法
- KMP算法
- KMP算法
- KMP算法
- KMP算法
- KMP 算法
- kmp算法
- KMP算法
- kmp算法
- KMP算法
- KMP算法
- kmp算法
- kmp算法
- KMP算法
- KMP算法
- NRF51822自学笔记(一) 流水灯
- 用消息队列和消息应用状态表来消除分布式事务
- sp指针
- YTU 2851: 数字游戏
- Spark算子:统计RDD分区中的元素及数量
- KMP算法
- mpich2 联机运行方法和问题2.
- 按钮和复选框控件
- MVC和MVP到底有什么区别呢?
- 43243
- Java序列化Serializable解析
- 使用 Environment Indicator 模块区分不同的 Drupal 环境
- AutoLayout
- 【Boost】boost库中thread多线程详解11——线程的休眠和中断