kmp hdu 3336

8 篇文章 0 订阅
#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

const int MAXN = 200010;

int next[MAXN];

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


int main()
{
    int T, i;
    cin>>T;
    char str[MAXN];
    while(T--)
    {
        int ans = 0;
        int n;
        cin>>n>>str;
        Get_Next(str, n);
        ans = next[n] + n;
        for(i = 0; i < n; ++i)
            if(next[i] > 0 && next[i] + 1 != next[i+1])
                ans += next[i];
        cout<<ans%10007<<endl;
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
KMP算法是一种字符串匹配算法,用于在一个字符串中查找另一个较短的模式串的出现位置。它的实现基于两个关键概念:部分匹配表和最大匹配前缀后缀数组(next数组)。通过构建next数组,KMP算法能够在失配时将模式串跳过一定长度,从而提高了匹配的效率。 在给定的引用内容中,有几个代码片段涉及到了使用Python实现KMP算法。这些代码分别是通过暴力搜索、利用next数组进行匹配以及计算next数组的实现。暴力搜索算法的时间复杂度为O(m*n),而KMP算法的时间复杂度为O(m+n),其中m为主串的长度,n为模式串的长度。 在KMP算法中,next数组记录了模式串中每个位置之前的最长公共前缀和最长公共后缀的长度。通过根据next数组的值来调整模式串的位置,KMP算法能够避免不必要的比较,从而提高匹配效率。 因此,Python中的KMP算法可以通过构建next数组来实现,在匹配过程中根据失配时的next值进行模式串的调整,直到找到匹配位置或匹配失败。这样可以在较短的时间内找到模式串在主串中的位置。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [KMP算法(python)](https://download.csdn.net/download/weixin_38618540/14854290)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [KMP算法(Python)](https://blog.csdn.net/m0_52238102/article/details/115830347)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值