您的位置:首页 > 其它

【模式串个数匹配】+ KMP

2017-04-10 21:18 169 查看
实现代码 :

#include<iostream>
#include<cstring>
using namespace std;
typedef struct{
int l;
char c[100];
}node;
int nx[100];
void pz(node &p,char *s){
if(strlen(s) > 100) return ;
p.l = strlen(s);
for(int i = 0 ; i < p.l; i++)
p.c[i] = *(s + i);
}
void qn(node p){
nx[1] = 0;
for(int i = 1,j = 0; i < p.l; i++){
j = nx[i];
while(j && p.c[i] != p.c[j]) j = nx[j];
nx[i + 1] = p.c[i] == p.c[j] ? j + 1 : 0;

}
}
int kmp(node a,node b,int pl){
for(int i = pl,j = 0; i < b.l; i++){
while(j && a.c[j] != b.c[i]) j = nx[j];
if(a.c[j] == b.c[i]) j++;
if(j == 3) return i + 1;
}
return 0;
}
int main()
{
node s;
pz(s,"bbaaabbababba");
node T;
qn(s);
pz(T,"abb") ;
int num = 0,pl = 0;
while(s.l - pl >= T.l){
pl = kmp(T,s,pl);
if(!pl) break;
num++;
}
cout << num << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  kmp