C语言KMP算法以及寻找next算法的实现
- KMP算法的实现 KMP算法:在大串中是否能找到小串 如找到 返回小串在大串中的位置
- 主要有两个算法:一个是KMP算法 一个是确定next数组的算法
下面展示一些 代码。
// KMP算法的实现 KMP算法:在大串中是否能找到小串 如找到 返回小串在大串中的位置
// 主要有两个算法:一个是KMP算法 一个是确定next数组的算法
// 字符数组输出采用 以下两种方法 都可以:
//char str[N];
// scanf("%s",str + x);
//cin >> str + x;//这两种输入方式都可行
//参考链接
/*
https://blog.youkuaiyun.com/wsmazh/article/details/113049924?ops_request_misc=&request_
id=&biz_id=102&utm_term=C%E8%AF%AD%E8%A8%80%E8%BE%93%E5%85%A5%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%
B8%8B%E6%A0%87%E4%BB%8E1%E5%BC%80%E5%A7%8B%E3%80%81&utm_medium=distribute.pc_search_result.none
-task-blog-2~all~sobaiduweb~default-0-113049924.first_rank_v2_pc_rank_v29_10
*/
#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
#define MAXSIZE 255
S.length = 0;
}
void GetLength(SString &S){
S.length = strlen(S.ch+1);//因为输入的时候下标就是从1开始输入的
}
//模式串的next数组
void GetNext(SString T, int next[]){
GetLength(T);
int i = 1, j = 0;//令i = 1 是让数组下标直接从1开始比较 不管为0的下标 符合输入的规则
next[1] = 0;
while(i < T.length){// <=
if(j == 0 || T.ch[i] == T.ch[j]){
++i;
++j;
next[i] = j;
}
else{
j = next[j];
}
}
// return ;
}
//S是主串 T是模式串
int KMP(SString S, SString T){
GetLength(S);
GetLength(T);
int next[T.length + 1];
int i = 1, j = 1;
// 令 i = 1 是让ch数组下标直接从1开始比较 不管为0的下标 符合输入的规则
// 令 j = 1 是让next数组下标从1开始记录
GetNext(T, next);
while(i <= S.length && j <= T.length){
if(j == 0 || S.ch[i] == T.ch[j]){
++i;
++j;
}
else{
j = next[j];
}
}
for(int k = 1; k < T.length+1; k++){//令 k < T.length+1 是为了让数组下标刚好为 T.length 的元素输出
cout<<next[k]<<" ";
}
cout<<endl;
if(j > T.length){
return i - T.length;
}else{
return 0;
}
}
int main(){
SString S;
InitString(S);
SString T;
InitString(T);
int check;
cout<<"请输入主串: \n";
cin>>S.ch+1;
cout<<"请输入模式串: \n";
cin>>T.ch+1;
check = KMP(S, T);
if(check == 0){
cout<<"没有找到匹配的子串!\n";
}
else{
cout<<"成功找到相匹配的子串,并且在主串中的序号为:"<<check<<endl;
}
cout<<S.ch+1<<endl;
cout<<T.ch+1<<endl;
GetLength(S);
GetLength(T);
cout<<S.length<<endl;
cout<<T.length<<endl;
return 0;
}