串2 串的模式匹配算法(KMP)

#include <stdio.h>

#define MAXSTRLEN 255
typedef unsigned char SString[MAXSTRLEN + 1];

void get_next(SString T, int next[]){
    int 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(SString T, int nextval[]){
    int i = 1, j = 0;
    nextval[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 = nextval[j];
    }
}

int Index_KMP(SString S, SString T, int pos){
    int i = pos, j = 1;
    int N = T[0];
    int next[N];
    get_nextval(T, next);        //可以替换为getnext() 
    
    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;
}

void StrAssign(SString S, char str[]){
    int i = 0;
    char * c = str;
    while (* c != '\0'){
        c++;
        i++;
    }
    S[0] = i;
    for(int j = 1; j <= i; j++){
        S[j] = str[j - 1];
    }
}

int main(){
    char a[] = "acabaabaabcacaabc";
    char b[] = "abaabcac";
    
    SString S, T;
    StrAssign(S, a);
    StrAssign(T, b);
    
    int pos = Index_KMP(S, T, 1);
    printf("%d", pos);
    
    return 0;
}

最近更新

  1. TCP协议是安全的吗?

    2024-06-10 23:00:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-10 23:00:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-10 23:00:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-10 23:00:02       18 阅读

热门阅读

  1. QT知识积累:qt取整函数

    2024-06-10 23:00:02       14 阅读
  2. MyBatis面试题系列三

    2024-06-10 23:00:02       8 阅读
  3. 高温应用中理想的油封材料选择

    2024-06-10 23:00:02       8 阅读
  4. Android基础-HIDL详述

    2024-06-10 23:00:02       9 阅读
  5. .net后端程序发布到nignx上,通过nginx访问

    2024-06-10 23:00:02       9 阅读
  6. 7、Spring之Bean生命周期~初始化

    2024-06-10 23:00:02       8 阅读
  7. Spring 冷知识:利用 @Profile 实现 AOP 的预先配置

    2024-06-10 23:00:02       11 阅读
  8. 京东一面测开(KPI)

    2024-06-10 23:00:02       10 阅读
  9. 构建高效爬虫系统:设计思路与案例分析

    2024-06-10 23:00:02       10 阅读
  10. 速览三版HTTP的改进策略

    2024-06-10 23:00:02       7 阅读
  11. 困难 Leetcode 312. 戳气球 区间dp/记忆化搜索

    2024-06-10 23:00:02       8 阅读
  12. 力扣22. 括号生成

    2024-06-10 23:00:02       10 阅读
  13. Leetcode 3177. Find the Maximum Length of a Good Subsequence II

    2024-06-10 23:00:02       15 阅读
  14. 力扣1234.替换子串得到平衡字符串

    2024-06-10 23:00:02       7 阅读
  15. C# —— 二维数组

    2024-06-10 23:00:02       8 阅读