算法竞赛_KMP算法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34686440/article/details/70884862
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;


#define MAX 255
char temp1[MAX];
char S[MAX];


char temp2[MAX];
char T[MAX];
//初始化ST 
void Init_ST(){
scanf("%s",temp1);
int n = strlen(temp1);
S[0] = n;
for(int i = 0;i<n;i++){
S[i+1] = temp1[i];
}

scanf("%s",temp2);
n = strlen(temp2);
T[0] = n;
for(int i = 0;i<n;i++){
T[i+1] = temp2[i]; 
}
}


//获取next【】数组
void get_next(char *T,int next[]){
next[1] = 0;
int i = 1;//后缀 
int j = 0;//前缀 

while(i<T[0]){
if(j == 0 || T[i] == T[j]){
++i;
++j;
next[i] = j;
}
else{
j = next[j];
}
}

//获取next数组之后的KMP算法
int Index_KMP(char *S,char *T,int pos){
//pos表示从主串的哪一个位置进行匹配
int i = pos;
int j = 1;
//调用get_next函数获取数组 
int next[MAX];
get_next(T,next);

while(i<=S[0] && j <= T[0]){
if(j == 0 || S[i] == T[j]){
++i;
++j;
}
else{
j = next[j];
}
}
if(j>T[0]) return i-T[0]; //表示匹配成功
else return 0; 
}




int main(){
Init_ST();//初始化主串和子串 
printf("%d\n",Index_KMP(S,T,1)); 
return 0;

猜你喜欢

转载自blog.csdn.net/qq_34686440/article/details/70884862
今日推荐