用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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章