串的模式匹配(基于修正的KMP的匹配算法)

#include
#include
#include
#include
#include
#define ElemType char

typedef struct
{
	ElemType *start;//顺序字符串的起始位置
	int length;//字符串的长度,即串中的字符个数
}CommonStr;

int nextval[20]={0};//用于存放模式串的next值的数组

int CreateStr(CommonStr &pstr, int n)//生成用于测试的主串
{
	pstr.start=(ElemType *)malloc(100*sizeof(ElemType));
	int i, k=0;
	pstr.length=0;
	srand((unsigned)time(NULL));
	for(i = 0; i < n; i++)
	{
		pstr.start[i] = (char)(rand()%2 + 'a');
		pstr.length++;
	}
	pstr.start[i] = '\0';
	return 1;
}

int GetNextval(CommonStr str)
{//求模式串的next函数值并存入数组next中
	int j = 0, k = -1; nextval[0] = -1;
	while(j < str.length)
	{
		if(k == -1 || str.start[k] == str.start[j])
		{
			++k; ++j;
			if(str.start[j] != str.start[k])
				nextval[j]=k;
			else
				nextval[j]=nextval[k];
		}
		else k=nextval[k];
	}
	printf("求得模式串的next数组为:\n\n");
	for(k = 0; k < 4; k++)
	{
		printf("%d - ", nextval[k]);
	

你可能感兴趣的:(剑指offer-算法与数据结构)