已传入github,可下载,想测试对应函数,调用传参即可,记得注释掉之前的主函数
文件名为2022_1_19,因为是是那天写的
GitHub - frankRenlf/c_programshttps://github.com/frankRenlf/c_programs.git部分代码如下:
我使用了两种方法写KMP算法,前一种参考了网上其他人的写法,不过重点在后面mykmp函数上,
个人认为用动态内存的方法更好,节省空间,并优化了计算速度.
其中nextval可以节省大量运行时间,极大提升函数在面对某些cases的运行速度.你们可以好好想想怎么提升的.
void Next(char* T, int* next) {
int i = 1;
next[1] = 0;
int j = 0;
while (i < strlen(T)) {
if (j == 0 || T[i - 1] == T[j - 1]) {
i++;
j++;
next[i] = j;
}
else {
j = next[j];
}
}
}
int KMP(char* S, char* T) {
int next[10];
Next(T, next);//根据模式串T,初始化next数组
int i = 1;
int j = 1;
while (i <= strlen(S) && j <= strlen(T)) {
//j==0:代表模式串的第一个字符就和当前测试的字符不相等;
//S[i-1]==T[j-1],如果对应位置字符相等,两种情况下,指向当前测试的两个指针下标i和j都向后移
if (j == 0 || S[i - 1] == T[j - 1]) {
i++;
j++;
}
else {
j = next[j];//如果测试的两个字符不相等,i不动,j变为当前测试字符串的next值
}
}
if (j > strlen(T)) {//如果条件为真,说明匹配成功
return i - j;
}
return -1;
}
void myNext(const char* sub, int* next, int len_sub)
{
next[0] = -1;
if (len_sub == 1)
{
return;
}
next[1] = 0;
int i = 2;
int k = 0;
while(i < len_sub)
{
if (k == -1 || sub[i - 1] == sub[k])
{
next[i] = k + 1;
i++;
k++;
}
else
{
k = next[k];
}
}
}
void myNextval(const char* sub, int* nextval, int* next, int len_sub)
{
nextval[0] = next[0];
for (int i = 1; i < len_sub; i++)
{
if (sub[i] == sub[next[i]])
{
nextval[i] = nextval[next[i]];
}
else
{
nextval[i] = next[i];
}
}
}
int myKMP(const char* str, const char* sub, int pos)
{
assert(str && sub);
int len_str = strlen(str);
int len_sub = strlen(sub);
if (len_str == 0 || len_sub == 0)
{
return -1;
}
if (pos<0 || pos>len_str)
{
return -1;
}
int* next = (int*)malloc(sizeof(int) * len_sub);
int* nextval = (int*)malloc(sizeof(int) * len_sub);
assert(next && nextval);
myNext(sub, next, len_sub);
myNextval(sub, nextval, next, len_sub);
int i = pos;
int j = 0;
while (i < len_str && j < len_sub)
{
if (j == -1 || str[i] == sub[j])
{
i++;
j++;
}
else
{
j = nextval[j];
}
}
free(next);
free(nextval);
if (j >= len_sub)
{
return i - j;
}
else
{
return -1;
}
}
有问题可在评论指出,觉得还行就给个赞和关注吧
也可以关注这个系列,后续也会有更新,和其他代码产出