【C语言】【数据结构】串的模式匹配算法(计算next、KMP算法)

1.录入多个字符串计算并验证NEXT值,输入0结束。
2.用KMP算法对主串和模式串进行模式匹配。

#include 
#include 
#define MAXSTRLEN 255

typedef unsigned char SString[MAXSTRLEN+1];

void get_next(SString , int *);
int Index_KMP(SString , SString );

int main()
{
	SString T, S;
	char ch;
	int n, i, j;
	int pos;
	
	printf("请输入需要匹配的字符串对数: \n");
	scanf("%d", &n);
	ch = getchar();
	for(i=1; i<=n; i++)
	{
		ch = getchar();
		for(j=1; j<=MAXSTRLEN && ch!='\n'; j++)
		{
			S[j] = ch;
			ch = getchar();
		}
		S[0] = j-1;
		ch = getchar();
		for(j=1; j<=MAXSTRLEN && ch!='\n'; j++)
		{
			T[j] = ch;
			ch = getchar();
		}
		T[0] = j-1;
		pos = Index_KMP(S,T);
		printf("%d\n", pos);
	}
}

void get_next(SString T, int next[])
{
	int i, j;
	
	next[1] = 0;
	i = 1; j = 0;
	while(i<T[0])
	{
		if(j==0 || T[i]==T[j])
		{
			i++; j++;
			next[i] = j;
		}
		else j = next[j];
	}
}

int Index_KMP(SString S, SString T)
{
	int next[MAXSTRLEN];
	int i, j;
	
	get_next(T, next);
	i = 1; j = 1;
	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;
}

你可能感兴趣的:(数据结构,C)