KMP求法(通过next)
2010-10-03 11:22
190 查看
// 用next求kmp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
void get_next(char T[],int next[]){
//求模式串T的next函数值并存入数组next
int i=1;next[1]=0;
int j=0;
int n;
n=strlen(T);
while(i<n){
if(j==0 || T[i]==T[j]) {++i;++j;next[i]=j;}
else j=next[j];
}
}
int Index_KMP(char S[],char T[],int pos,int next[]){
//利用模式串T的next函数求T在主串中第pos个字符之后的位置的
//KMP算法.其中,T非空,1<=pos<=StrLength(S).
int i=pos;
int j=1;
int m,n;
m=strlen(S);
n=strlen(T);
while(i<=m && j<=n){
if(j==0 || S[i]==T[j]){++i;++j;}//继续比较后续字符
else j=next[j];
}
if(j>n) return i-n;//匹配成功
else return 0;
}
int main(int argc, char* argv[])
{
char CS[100],char CT[100];
int data,data1,ne[100];
cout<<"请输入主串"<<endl;
cin>>CS;
cout<<"请输入子串"<<endl;
cin>>CT;
cout<<"请输入主串中从第pos个字符开始匹配的"<<endl;
cin>>data;
get_next(CT,ne);
data1=Index_KMP(CS,CT,data,ne);
cout<<data1<<endl;
return 0;
}
//
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
void get_next(char T[],int next[]){
//求模式串T的next函数值并存入数组next
int i=1;next[1]=0;
int j=0;
int n;
n=strlen(T);
while(i<n){
if(j==0 || T[i]==T[j]) {++i;++j;next[i]=j;}
else j=next[j];
}
}
int Index_KMP(char S[],char T[],int pos,int next[]){
//利用模式串T的next函数求T在主串中第pos个字符之后的位置的
//KMP算法.其中,T非空,1<=pos<=StrLength(S).
int i=pos;
int j=1;
int m,n;
m=strlen(S);
n=strlen(T);
while(i<=m && j<=n){
if(j==0 || S[i]==T[j]){++i;++j;}//继续比较后续字符
else j=next[j];
}
if(j>n) return i-n;//匹配成功
else return 0;
}
int main(int argc, char* argv[])
{
char CS[100],char CT[100];
int data,data1,ne[100];
cout<<"请输入主串"<<endl;
cin>>CS;
cout<<"请输入子串"<<endl;
cin>>CT;
cout<<"请输入主串中从第pos个字符开始匹配的"<<endl;
cin>>data;
get_next(CT,ne);
data1=Index_KMP(CS,CT,data,ne);
cout<<data1<<endl;
return 0;
}
相关文章推荐
- POJ2752_通过kmpNext数组的性质求一个字符串的公共同前后缀
- Simpsons’ Hidden Talents(KMPnext[]的应用)
- 手算KMP匹配的Next值和Nextval值
- POJ 2752 Seek the Name, Seek the Fame(KMP next数组运用)
- KMP的next[]的求解方法
- hdu1358 kmp的next数组求循环节
- 【经典算法】——KMP,深入讲解next数组的求解
- poj 2752 KMP的next数组应用(prefix-suffix string)
- 【经典算法】——KMP,深入讲解next数组的求解
- POJ - 2752 Seek the Name, Seek the Fame(KMP中对next数组的前缀后缀匹配应用)
- HDU 3746 KMP_Next 找循环节
- 通过kmp的失配数组来求解字符串的循环节
- 【经典算法】——KMP,深入讲解next数组的求解
- 【经典算法】——KMP,深入讲解next数组的求解
- POJ 2752: S 4000 eek the Name, Seek the Fame(简单KMP-NEXT数组的应用)
- #1015 : KMP算法(kmp裸题,把next数组定义成了char类型,wa了半天 )
- poj2406--kmp next的应用
- poj 2406 Power Strings[kmp,next数组的应用]
- poj 2406 Power Strings(KMPnext性质)
- HDU3336 KMP之next数组妙用