学习目标:
串的基本操作
KMP算法的原理和代码
学习内容:
串的定长储存结构
串的变长储存结构
串的赋值
取串长度操作
串的比较操作
串连接操作
求子串操作
串清空操作
基础算法匹配
KMP算法
学习时间:
2021.4.4到2021.4.5 am12:00
学习产出:
串的定长储存结构:
//串的定长储存结构表示
typedef struct
{
char str[maxsize + 1];//maxsize表示串的最大长度 以“/0”作为结束符号 所以maxsize +1
int length;
}Str;
串的变长储存结构:
//变长分配储存结构表示
typedef struct
{
char * ch;
int length;
}Str;
串的赋值:
//赋值操作
int strassign(&Str, char* ch)
{
if (str.ch)
free(str.ch);
int len = 0;
char* c = ch;
while (*c)
{
++len;
++c;
}
if (len == 0)
{
str.ch = NULL;
str.leng = o;
return 1;
}
else
{
str.ch = (char*)malloc(sizeof(char) * (len + 1));//加1是因为“\0”
if(str.ch == NULL)
return 0;
else
{
c = ch;
for (int I = 0; I <= LEN; ++i, ++c)//<=是因为 同上
str.ch[i] = *c;
str.length = len;
return 1;
}
}
}
取串长度操作:
//取串长度操作
int strlength(Str str)
{
return str.length;
}
串比较操作;
//串比较操作
int strconmpare(Str s1, Str s2)
{
for (int i = 0; i < s1.length && i < s2.length; ++i)
if (s1.ch[i] != s2.ch[i])
return s1.ch[i] - s2.ch[i];
return s1.length - s2.length;
}
求子串操作:
//求子串操作
int substring(Str& substr, Str str, int pos, int len)
{
if (pos < 0 || pos >= str.length || len<0 || len>str.length - pos)
rerurn 0;
if (substr.ch)
{
free(substr.ch)
substr.ch = NULL;
}
if (len = 0)
{
substr.ch = NULL;
substr.length = 0;
return 1;
}
else
{
substr.ch = (char*)malloc(sizeof(char) * (len + 1));
int i = pos;
int j < 0;
while (i < pos + len)
{
substr.ch[j] = str.ch[i];
++i;
++j;
}
substr.ch[j] = '\0';
substr.length = len;
return 1;
}
}
串连接的操作:
//串连接操作
int concat(Str& str, Str strl, Str str2)
{
if (str.ch)
{*-
free(str.ch);//释放原串空间
str.ch = NULL;
}
str.ch = (char*)malloc(sizeof(char) * (strl.length + str2.length + 1));
if (str.ch == NULL)
{
return 0;
}
int i = 0;
while (i < strl.length)
{
str.ch[i] = strl.ch[i];
++i;
}
int j = 0;
while (j <= str2.ch[j])
{
str.ch[i + j] = str2.ch[j];
++j;
str.length = strl.length + str2.length;
return 1;
}
}
串清空操作:
//串清空操作
int cleanstring(Str& str)
{
if (str.ch)
{
free(str.ch)
str.ch = NULL;
}
str.length = 0;
return 1;
}
基础算法匹配:
//算法匹配(简单)
int index(Str str,Str substr)
{
int i = 1, j = 1, k = 1;//串从数组的下标1开始储存,因此为1
while (i <= str.length && j <= substr.length)
{
if (str.ch[i] == substr.ch[i])
{
if (str.ch[i] == substr.ch[j])
{
++i;
++j;
}
else
{
j = 1;
j = ++k;
}
}
}if (j > substr.length)
return k;
else
return 0;
}
KMP算法:
//kmp
//next数组的变化计算
void getnext(Str substr, int next[j])
{
int i = 1, j = 0;//串从数组下标的位置开始储存,因此i的初值为1
next[i] = 0;
while (i < substr.length)
{
if (j == 0 || substr.ch[i] == substr.ch[j])
{
++i;
++j;
next[i] = j;
}
else
j = next[j];
}
}
int KMP(Str str, Str substr, int next[])
{
int i = 1, j = 1;
while (i < substr.length && j <= substr.length)
{
if (j == 0 || substr.ch[i] == substr.ch[j])
{
++i;
++j;
next[i] = j;
}
else
j = next[j];
}
if (j > substr.length)
return i - substr.length;
else
return 0;
}
参考书目
《2022数据结构高分笔记》 ——率辉