美文网首页
c语言实现KMP算法

c语言实现KMP算法

作者: 一路向后 | 来源:发表于2021-03-18 21:25 被阅读0次

1.源码实现

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void getnext(const char *temp, int *f)
{
    int n = strlen(temp);
    int i, j;

    f[0] = f[1] = 0;

    for(i=1; i<n; i++)
    {
        j = f[i];

        while(j && temp[i] != temp[j])
        {
            j = f[j];
        }

        f[i+1] = temp[i] == temp[j] ? j + 1 : 0;
    }
}

void findstr(const char *str, const char *temp, int *f)
{
    int n = strlen(str);
    int m = strlen(temp);
    int i, j = 0;

    /*生成next数组*/
    getnext(temp, f);

    for(i=0; i<n; i++)
    {
        /*不停地转移, 直到可以匹配或者走到0*/
        while(j && str[i] != temp[j])
        {
            j = f[j];
        }

        /*如果相等, 模板串中待匹配位置可以移一位了*/
        if(str[i] == temp[j])
        {
            j++;
        }

        if(j == m)
        {
            printf("%d\n", i-m+1);
        }
    }
}

int main()
{
    char *a = "hello world";
    char *b = "llo";
    int c[100];

    memset(c, 0x00, sizeof(c));

    findstr(a, b, c);

    return 0;
}

2.编译程序

$ gcc -o example example.c

3.运行程序

$ ./example
2

相关文章

  • c语言实现KMP算法

    1.源码实现 2.编译程序 3.运行程序

  • KMP算法

    写在前面 这篇文章针对的是C/C++/Java语言程序,所以我们的下标从零开始。 KMP算法的改进 KMP算法的改...

  • Swift 实现KMP算法

    使用swift语言实现了一下KMP算法,具体代码如下 详细的描述了KMP算法推导next数组的流程 改进后的nex...

  • 字符串匹配与KMP算法

    1.朴素字符串匹配算法 2.KMP算法 求前缀函数 实现KMP算法 3.测试代码

  • KMP算法 C++实现

  • 算法(2)KMP算法

    1.0 问题描述 实现KMP算法查找字符串。 2.0 问题分析 “KMP算法”是对字符串查找“简单算法”的优化。 ...

  • KMP算法 理解与实现

    KMP算法,背景不必多说,主要想写一写自己对KMP算法的一些理解和其具体实现。关于KMP算法的原理,阮一峰老师的这...

  • KMP算法的理解及其C语言的实现

    KMP的概念网上有很多介绍,核心是理解PMT(Partial Match Table,部分匹配表),而next数组...

  • KMP算法

    参考文献1.B站灯笼哥2.KMP算法python实现3.如何更好的理解和掌握 KMP 算法?

  • Implement strStr()

    标签: C++ 算法 LeetCode 字符串 KMP 每日算法——leetcode系列 问题 Implemen...

网友评论

      本文标题:c语言实现KMP算法

      本文链接:https://www.haomeiwen.com/subject/svapcltx.html