kmp(C语言)

简单的模式匹配算法

int strStr(char * haystack, char * needle){
	int i=0,j=0;
	while(i<strlen(haystack)&&j<strlen(needle)){
		if(haystack[i]==needle[j]){
			i++;
			j++;
		}
		else{
			i=i-j+1;
			j=0;
		}
	}
	if(j==strlen(needle)) return i-j;
	else return -1;
}

KMP算法  next数组,就是求字符串的每个位置的最长公共前后缀,就是当匹配到i不匹配时,将字符串往后移,在i之前重合了多少位,在将重合后的以为j与i进行匹配,实现i不回溯,b站av16828557讲的太好了

#include<stdio.h>
#include<string.h>//kmp
#include<stdlib.h>
void next_i(char a[],int n,int next[]){
	int i=1,j=0;
	next[0]=0;
	while(i<n){
		if(a[i]==a[j]){
			j++;
			next[i]=j;
			i++;
		}
		else{
			if(j>0) j=next[j-1];
			else {
				next[i]=j;
				i++;
			}
		} 
	}
}
void move_next(int next[],int n){
	int i;
	for(i=n-1;i>0;i--)
		next[i]=next[i-1];
	next[0]=-1;
}
int strStr(char * haystack, char * needle){
	int i=0,j=0,m=strlen(haystack),n=strlen(needle);
	int *next;
	next=(int*)malloc(sizeof(int)*n);
	next_i(needle,n,next);
	move_next(next,n);
	while(i<m&&j<n){
		if(haystack[i]==needle[j]){
			i++;
			j++;
		}
		else{
			j=next[j];//如果不相等,j移到它所对应的最大后缀 
			if(j==-1){
				i++;
				j++;
			} 
		}
	}
	if(j==n) return i-j;
	else return -1;
}
int main(){
	char a[30],b[30];
	gets(a);
	gets(b);
	printf("%d ",strStr(a,b));
} 

不知道为什么在leetcode 上过不去

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值