匹配串 KMP算法

匹配串---基础写法 :

#include <stdio.h>
#include <string.h> //库函数
/*
    char * strstr(char *string, char *pattern);
*/
typedef char* Position; //重命名
#define NotFound NULL

int main()
{
    char string[] = "This is a simple example.";
    char pattern[] = "simple";
    Position p = strstr(string, pattern);
    printf("%s\n", p);
    return 0;
}

KMP算法 :

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

typedef int Position; //起别名
#define NotFound -1   //定义一个不可能是下标的量

void BuildMatch(char *pattern, int *match)
{
    Position i, j;
    int m = strlen(pattern);
    match[0] = -1;
    for (j = 1; j < m; j++)
    {
        i = match[j - 1];
        while ((i >= 0) && (pattern[i + 1] != pattern[j]))
            i = match[i];
        if (pattern[i + 1] == pattern[j])
            match[j] = i + 1;
        else
            match[j] = -1;
    }
}

Position KMP(char *string, char *pattern)
{
    int n = strlen(string);
    int m = strlen(pattern);
    Position s, p, *match;
    if (n < m)
        return NotFound;
    match = (Position *)malloc(sizeof(Position) * m);
    BuildMatch(pattern, match);
    s = p = 0;
    while (s < n && p < m)
    {
        if (string[s] == pattern[p])
        {
            s++;
            p++;
        }
        else if (p > 0)
            p = match[p - 1] + 1;
        else
            s++;
    }
    return (p == m) ? (s - m) : NotFound;
}

int main()
{
    //char string[] = "This is a simple example.";
    //char pattern[] = "sample";
    printf("请输入字符串1 :\n");
    char string[81];
    // scanf("%s",string);
    gets(string);
    //getchar();
    printf("请输入字符串2 :\n");
    char pattern[81];
    //scanf("%s",pattern);
    gets(pattern);
    //返回字符指针,只能处理字符串;返回数组下标,可处理任何类型串
    Position p = KMP(string, pattern); //返回数组下标

    if (p == NotFound)
        printf("NotFound.\n");
    else
        printf("字符串匹配成功:%s\n", string + p);

    return 0;
}
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

upward337

谢谢老板~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值