//4.1_1
/*串的定义和基本操作
* StrAssign(&L,chars):赋值操作
* StrCopy(&T,s):复制操作
* StrEmpty(S):判空操作
* StrLength(S):求串长
* ClearString(&S):清空操作
* DestoryString(&S):销毁串
* Concat(&T,S1,S2):串连接;用T返回由S1和S2连接而成的字串
* SubString(&Sub,S,pos,len):求子串;用Sub返回串S的第pos个字符起长度为len的子串;
* Indes(S,T):定位操作;若主串S中存在与串T相同的字串,则返回它在主串S中第一次出现的位置;否则函数值为0;
* StrCompare(S,T):比较操作。若S>T,则返回值>0;若S<T,则返回值<0;若S=T,则返回值=0;
*/
//4.1_2串的存储结构
//1.串的顺序存储
#define MAXLEN 255
typedef struct {
char ch[MAXLEN];//静态数组实现(定长顺序存储)
int length;
}SString;
//动态数组实现(堆分配存储)
typedef struct {
char *ch;//按串长分配存储区,ch指向串的基地址
int length;
}HString;
HString S;
S.ch = (char*)malloc(MAXLEN * sizeof(char));//用完需要手动free
S.length = 0;
//2.串的链式存储
typedef struct {
char ch;//每个结点存一个字符
struct StringNode *next;
}StringNode,* String;
typedef struct {
char ch[4];//每个结点存多个字符
struct StringNode* next;
}StringNode, * String;
//基本操作实现
#define MAXLEN 255
typedef struct {
char ch[MAXLEN];//静态数组实现(定长顺序存储)
int length;
}SString;
//求子串
bool SubString(SString& Sub, SString S, int pos, int len) {
if (pos + len - 1 > S.length)
return false;
for (int i = pos; i < pos + len; i++)
Sub.ch[i - pos + 1] = S.ch[i];
Sub.length = len;
return true;
}
//比较操作
int StrCompare(SString S, SString T) {
for (int i = 1; i <= S.length && i <= T.length; i++) {
if (S.ch[i] != T.ch[i])
return S.ch[i] - T.ch[i];
}
return S.length - T.length;
}
//定位操作
int Index(SString S, SString T) {
int i = 1, n = Strlength(S), m = StrLength(T);
SString sub;
while (i <= n - m + 1) {
SubString(sub, S, i, m);
if (StrCompare(sub, T) != 0)
++i;
else
return i;
}
return 0;
}
//4.2_1朴素模式匹配算法
int Index(SString S, SString T) {
int i = 1, j = 1;
while (i <= S.length && j <= T.length) {
if (S.ch[i] == T.ch[i]) {
++i; ++j;
}
else {
i = i - j + 2;//匹配失败时,主串指针疯狂回溯
j = 1;
}
}
if (j > T.length)
return i - T.length;//当前字串匹配成功,返回当前字串第一个字符的位置i-T.length
else
return 0;
}
//4.2_2 KMP算法
int Index(SString S, SString T) {
int i = 1, 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不回溯
}
}
if (j > T.length)
return i - T.length;//当前字串匹配成功,返回当前字串第一个字符的位置i-T.length
else
return 0;
//next[]数组408只要求手算选择题;但另附代码
void get_next(String T, int next[]){
int i = 1, j = 0;
next[1] = 0;
while (i < T.length) {
if (j == 0 || T.ch[i] == T.ch[j])
++i; ++j;
next[i] = j;
}
else
j = next[j];
}
//4.2_3 KMP算法的进一步优化
void get_nextval(String T, int nextval[]) {
int i = 1; j = 0;
nextval[1]; v
while (i < T.length) {
if (j == 0 || T.ch[i] != T.ch[j])
nextval[i] = j;
else
j = nextval[j];
}
}
//先求出next[]数组,再求出nextval[]数组;
nextval[1] = 0;
for(int j=2;j<=T.length;j++){
if (T.ch[next[j]] == T.ch[j])
nextval[j] = nextval[next[j]];
else
nextval[j] = next[j];
02-06
422
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-14
598
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)