串相關操作的算法總結

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];
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章