串相关操作的算法总结

1.串的顺序存储

//串的定长顺序存储结构
#define MAXLEN 255
typedef struct
{
	char ch[MAXILEN+1];	// 存储串的一维数组
	int length;         //串的当前长度
}SString;

//串的堆式顺序存储结构
typedef struct
{
	char *ch;			// 若非空串,按串长分配空间;否则ch = NULL
	int length;
}HString;

2.串的链式存储结构

#define CHUNKSIZE 80   	//可由用户定义的块大小
typedef struct Chunk{
   char  ch[CHUNKSIZE];
   struct Chunk *next;
}Chunk;

typedef struct{
   Chunk *head,*tail; 	//串的头指针和尾指针
   int curlen; 			//串的当前长度
}LString;				//尾指针的目的是为了便于进行联结操作。

3.BF算法

int index(SString S,SString T,int pos)
{
	i = pos; j = 1;
	while(i<=S.length && j<=T.length)
	{
		if(S.ch[i] == T.ch[j])
		{
			++i;++j;
		}
		else
		{
			i=i-j+1;
			j=1;
		}
		if ( j>T.length)   
			return   i-T.length;
		else 
			return 0;
	}
}

4.KMP算法

int Index_KMP(SString S,SString T,int pos)
{	
	i = pos; j = 1;
	while(i<=S.length && j<=T.length)
	{
		if(j==0 || S.ch[i]==T.ch[j])
		{
			++i;++j
		}
		else
			j = next[j];     //i不变,j后退
	}
	if(j>T.length)
		return i-T.length;   //匹配成功
	else
		return 0;			 //匹配失败
}

void get_next(SString P,int &next[])
{
	j = 1; next[j] = 0; k = 0;
	while(j<P.length)
	{
		if(k==0 || P.ch[j] == P.ch[k])
		{
			++j;++k;
			next[j] = k;
		}
		else
			k = next[k];
	}
}

void get_nextval(SString P,int &nextval[])
{
	j = 1; nextval = 0; k = 0;
	while(j<P.length)
	{
		if(k==0 || P.ch[j] == P.ch[k])
		{
			++j;++k;
			if(P.ch[j] != P.ch[k])
				nextval[j] = k;
			else
				nextval[j] = nextval[k];
		}
		else
			k = nextval[k];
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章