最长字符串匹配算法(KMP算法)
来源:互联网 发布:ai mac版 编辑:程序博客网 时间:2024/04/30 21:00
最长字符串匹配算法(KMP算法)
#include "stdafx.h"
#include<iostream>
#include<time.h>
#include<string>
using namespace std;
void init(string ,string);
void show(char [],int);
int kmp(string ,string,int pos);
void get_next(char*,int *);
string s1,t1;
int m,n;
char *s;
char *t;
int *next;
/*************************MAIN**************************************/
int main(int argc[],char*args[])
{
double t=clock();
cout<<"起始时间:"<<t<<endl;
cout<<"找到位置为:"<<kmp("acbsabcaacabaabaabcacaabc","abaabca",1)<<endl;
delete[] s;
delete[] next;
cout<<"结束时间:"<<clock()<<endl;
cout<<"耗时:"<<(clock()-t)/1000<<"毫秒!"<<endl;
return 0;
}
/**********************++++NEXT++++********************************/
void get_next(char s[],int ne[])
{
ne =new int[n+1];
next=new int[n+1];
ne[0]=9999;
int i(1),j(0);
ne[1]=0;
while(i<=(int)(t[0]))//数组是字符型的,要转化为整数
{
if(j==0||t[i]==t[j]){++i;++j;ne[i]=j;}
else j=ne[j];
}
for( i=1;i<=n;i++)
{
cout<<"next["<<i<<"]="<<ne[i]<<endl;
next[i]=ne[i];
}
}
/********************++++KMP+++**********************************/
int kmp(string s0,string t0,int pos)
{
init(s0,t0);
int i=pos,j=1;
while(i<=((int)(s[0]))&&(j<=((int)(t[0]))))
{
if((j==0)||(s[i]==t[j])){++i;++j;}
else j=next[j];
}
if(j>(int)(t[0])) return i-((int)(t[0]));
else return 0;
}
/***************++++INIT+++*****************************************/
void init(string ss,string tt)
{
//cout<<"请输入原串S=: "<<endl;
//cin>>s1;
//cout<<"请输入模式串T=:"<<endl;
//cin>>t1;
s1=ss;
t1=tt;
m=s1.length();
n=t1.length();
//if((s=(char*)malloc((m+1)*sizeof(char)))<0){cout<<"failed\n";return;}
s=new char[m+1];
s[0]=m;
//if((t=(char*) malloc((n+1)*sizeof(char)))<0) {cout<<"failed\n";return;}
t=new char[n+1];
t[0]=n;
for(int i=1;i<=m;i++)
s[i]=s1.at(i-1);
for( i=1;i<=n;i++)
t[i]=t1.at(i-1);
cout<<"原串为: "; show(s,m);
cout<<"模式串为: "; show(t,n);
get_next(t,next);
}
/*******************++++SHOW+++**************************************/
void show(char s[],int n )
{
for(int i=1;i<=n;i++)
cout<<s[i]<<" ";
cout<<endl;
cout<<"长度为: "<<int(s[0])<<"\n";
}
- 最长字符串匹配算法(KMP算法)
- 字符串匹配(KMP算法)
- 字符串匹配算法(KMP)
- kmp算法(字符串匹配)
- 字符串匹配(KMP算法)
- KMP算法(字符串匹配)
- 字符串匹配(KMP算法)
- KMP 字符串匹配算法
- kmp字符串匹配算法
- kmp字符串匹配算法
- KMP字符串匹配算法
- 字符串匹配算法-kmp
- KMP(字符串匹配)算法
- KMP 字符串匹配算法
- 字符串匹配算法:KMP
- KMP算法 字符串匹配
- 字符串匹配 KMP 算法
- KMP字符串匹配算法
- cocos2d 坐标系
- Oracle Data Integrator 介绍
- SRM 593 Div1 L1:HexagonalBoard,用染色法判断无向图是否为二分图
- Red hat AS oracle11g 手工创建OEM
- 软件架构师需要掌握哪些知识?
- 最长字符串匹配算法(KMP算法)
- UVA - 10558 A Brief Gerrymander
- 鼠标放上去显示全部文字,不放上去,显示部分文字jquery效果,包括隐藏部分文字
- 怎样找到sql报错的存储过程和触发器及语句
- 设计jquery插件
- STL vector常用的几个成员的用法
- 2 synchronized 和 Lock+Condtion 对比
- 28岁的我站在人生十字路口该怎么走?
- CODE 77: Merge Intervals