一、串的存储方式
1.顺序存储方式
#define MAXLEN 100
typedef struct
{
char str[MAXLEN];
int curlen; /* data */
}string;//顺序存储结构
2.链式存储结构(块链)
typedef NODELEN 100
typedef struct node
{
char ch;//链式存储结构
char ch[NODELEN];//块链
struct node *next;
} node, *pointer;
typedef struct
{
pointer head, tail;
int length;
}linkedstring;
二、串的模式匹配算法
1.朴素的模式匹配算法
//串的朴素匹配算法
int Index(String S,String T,int pos)
{
int i = pos;
int j = 1;
while(i<=S[0]&&j<=T[0])//假定字符串第一位存长度
{
if(S[i]==T[j])
{
i++;
j++;
}
else
{
i = i - j + 2;
j = 1;
}
}
if(j>T[0])
{
return i - T[0];
}
else
{
return 0;
}
}
2.KMP模式匹配算法(未修正+已修正)
//KMP算法
void get_next(String T,int *next)//算出模式串T的next数组
{
int i, j;
i = 1;
j = 0;
next[1] = 0;
while(i<T[0])//长度
{
if(j==0||T[i]==T[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
}
void get_nextval(String T,int *nextval)//算出模式串T的改进后的next数组
{
int i, j;
i = 1;
j = 0;
next[1] = 0;
while(i<T[0])//长度
{
if(j==0||T[i]==T[j])
{
i++;
j++;
if(T[i]!=T[j])//修改部分
nextval[i] = j;
else
{
nextval[i] = nextval[j];
}
}
else
{
j = next[j];
}
}
}
int Index_KMP(string S,Sting T,int pos)
{
int i = pos;
int j = 1;
int next[255];
get_next(T,next);
get_next_val(T,next);//修正后的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;
}