栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

数据结构KMP算法C语言实现

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构KMP算法C语言实现

最近学习数据结构串的匹配,王道书上只有伪代码实现,于是尝试写出可以运行的c语言代码。

#include 
#include 
#include 

void Next(char* T,int* next){//求next数组
	next[1]=0;
	next[2]=1;
	int j=1;
	int i=2;
	while(i
		if(j==0||T[j-1]==T[i-1]){
			i++;
			j++;
			if(T[j-1]!=T[i-1]){
				next[i]=j;
			}
			else{
				next[i]=next[j];
			}
		}
		else{
			j=next[j];
		}
	}
}

int KMP(char* S,char* T){//KMP算法实现
  	int next[10];
  	Next(T,next);
  	int i=1;
  	int j=1;
  	while(i<=strlen(S)&&j<=strlen(T)){
  	  		if(j==0||S[i-1]==T[j-1]){
  			i++;
  			j++;
		  }
		  else{
		  	j=next[j];
		  }
	  }
	  if(j>strlen(T)){
	  	return i-(int)strlen(T);
	  }
	  return -1;
}

int main(){
	char* source;
	source= (char*)malloc(100*sizeof(char));
    char* target;
	target= (char*)malloc(100*sizeof(char));
	gets(source);
	gets(target);
    int i=KMP(source,target);
	printf("%d",i);
	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/875635.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号