KMP 算法的应用

44 篇文章 3 订阅
23 篇文章 0 订阅

KMP算法的应用主要体现在Next数组的计算方式上。Next数组含义如下:
Next[i] = j, 表示下标 i 之前连续 j 个字符,和字符串开始的连续 j 个字符相同。这会带来很多应用。比如

1、POJ 2406:字符串乘方

#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>

using namespace std;

char str[1001000];
int _next[1001000];

void get_next(char *str)
{
    _next[0] = -1;
    int i = 0, k = -1, len = strlen(str);
    while(i < len)
    {
        while(k>=0 && str[i]!=str[k])
            k = _next[k];
        i++;
        k++;
        _next[i] = k;
    }
    for(int i=0;i<len;i++)
        _next[i] = _next[i+1];
}

int main()
{
    //freopen("in.txt", "r", stdin);

    while(scanf("%s", str) && str[0]!='.')
    {
        get_next(str);
        // cout<<"*********"<<endl<<str<<endl;
        // for(int i=0;i<strlen(str);i++)
        //  cout<<_next[i]<<" ";
        // cout<<endl;
        int len = strlen(str);
        if(_next[len-1]>0 && len%(len-_next[len-1]) == 0)
            printf("%d\n", len/(len-_next[len-1]));
        else
            printf("1\n");
    }
    return 0;
}

2、POJ 1961:前缀中的周期

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

using namespace std;

int n, case_num = 1;
int _next[1001000];
string str;

void get_next(string s)
{
    int len = s.length();
    int i = 0, k = -1;
    _next[0] = -1;

    while(i < len)
    {
        while(k>=0 && s[i]!=s[k])
            k = _next[k];
        i++;
        k++;
        _next[i] = k;
    }
    for(int i=0;i<len;i++)
        _next[i] = _next[i+1];
}

int main()
{
    //freopen("in.txt", "r", stdin);

    while(scanf("%d", &n) && n)
    {
        cin>>str;
        printf("Test case #%d\n", case_num);
        case_num++;
        int len = str.length();

        get_next(str);

        for(int i=0;i<len;i++)
        {
            int now_len = i+1;
            if(_next[i]>0 && now_len%(now_len-_next[i])==0)
                printf("%d %d\n", now_len, now_len/(now_len-_next[i]));
        }

        printf("\n");
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值