匹配串 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;
}
发布了36 篇原创文章 · 获赞 82 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44949135/article/details/105084880