I will not forget who I love.

Honor is in the heart.

数据结构-模式匹配串算法(KMP)

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>

using namespace std;

void getnext(char *t, int *next, int lent)
{
    int i = 0, j = -1;
    next[0] = -1;
    while (i < lent)
        if (j == -1 || t[i] == t[j])
            ++i, ++j, next[i] = j;
        else
            j = next[j];
}

int kmp(char *s, char *t, int *next, int lens, int lent)
{

    int i = 0, j = 0;
    while (i < lens)
    {
        if (-1 == j || s[i] == t[j])
            i++, j++;
        else
            j = next[j];
        if (j == lent) return 1;
    }
    return 0;
}



int main()
{
    char t[100],s[1000];
    int next[100];
    printf("Enter模式串,主串\n");
    scanf("%s",t);
    gets(s);
    int lent = strlen(t);
    int lens = strlen(s);
    getnext(t, next, lent);
    printf("%d\n1表示成功", kmp(s, t, next, lens, lent));
    return 0;
}

阅读更多
版权声明:Honor is in the heart. https://blog.csdn.net/DeathIsLikeTheWind/article/details/53982634
文章标签: 数据结构 KMP
个人分类: 写给自己
上一篇数据结构-哈夫曼(Huffman)
下一篇数据结构-多项式计算(栈实现)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭