用KMP算法查找字符串中字串位置

#include<stdio.h>


//i(后缀)
//j (前缀)
void get_next(char* T,int *next)
{
	int i = 1;
	int j = 0;
	next[1] = 0;
	while(i<T[0])
	{
  		if(j == 0|| T[i] == T[j])
	 	{
			i++;
			j++;
			if(T[i] != T[j])
			{
				next[i] = j;
			}
			else
			{
				next[i] = next[j];
			}
     		}	
		else
		{
			//j回溯
			j = next[j];
		}
	}
//前缀是固定的 ,后缀是相对的
}
//返回子串T在S中的位置
//在S串第pos个元素之后的位置
int index_KMP(char * S,char* T,int pos)
{
	int i = pos;
	int j = 1;
	int next[255];
	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()
{
	char str[255] = "abcdef";//第一个值忽略,记字符串长度
	str[0] = 6;
	char T[255] = "ade";//第一个值忽略,集字符串长度
	T[0] = 2;
	int num;
	num = index_KMP(str,T,1);
	printf("%d",num);
	return 0;
}

《用KMP算法查找字符串中字串位置》

    原文作者:KMP算法
    原文地址: https://blog.csdn.net/u013239402/article/details/43026939
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞