【2019杭电多校第五场1006=HDU6629】string matching(求后缀字符串和本串的最长公共前缀长度之和--扩展kmp)

本文深入解析了扩展KMP算法,一种用于解决字符串匹配问题的高效算法。通过对比传统暴力方法,详细阐述了扩展KMP算法的原理、实现过程及优化策略,特别强调了其在处理大量数据时的优势。并通过具体实例展示了算法的运行效果,为读者提供了清晰的代码实现和性能分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=6629

题目:


string matching

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)

Problem Description

String matching is a common type of problem in computer science. One string matching problem is as following:

Given a string s[0…len−1], please calculate the length of the longest common prefix of s[i…len−1] and s[0…len−1] for each i>0.

I believe everyone can do it by brute force.
The pseudo code of the brute force approach is as the following:



We are wondering, for any given string, what is the number of compare operations invoked if we use the above algorithm. Please tell us the answer before we attempt to run this algorithm.

Input

The first line contains an integer T, denoting the number of test cases.
Each test case contains one string in a line consisting of printable ASCII characters except space.

* 1≤T≤30

* string length ≤106 for every string

Output

For each test, print an integer in one line indicating the number of compare operations invoked if we run the algorithm in the statement against the input string.

Sample Input

3

_Happy_New_Year_

ywwyww

zjczzzjczjczzzjc

Sample Output

17

7

32

解题思路:


新算法get✅

扩展KMP裸题,不能用后缀数组,倍增算法nlogn超时,DC3算法常数过大,同样超时!!

扩展kmp讲解参见https://www.jianshu.com/p/107e47994d49

 

ac代码:


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1000010; //字符串长度最大值
int nxt[maxn];
char s[maxn];
ll  solve(char str[])
{
    ll ans = 0;
    int i=0,j,po,len=strlen(str);
    nxt[0]=len; //初始化nxt[0]
    while(str[i]==str[i+1] && i+1<len) i++; nxt[1]=i; //计算nxt[1]
    ans += nxt[1];
    if(nxt[1] != len - 1) ans++;
    po=1; //初始化po的位置
    for(i=2;i<len;i++)
    {
        if(nxt[i-po]+i < nxt[po]+po) //第一种情况,可以直接得到nxt[i]的值
            nxt[i]=nxt[i-po];
        else //第二种情况,要继续匹配才能得到nxt[i]的值
        {
            j = nxt[po]+po-i;
            if(j<0) j=0; //如果i>po+nxt[po],则要从头开始匹配
            while(i+j<len && str[j]==str[j+i]) j++; nxt[i]=j;
            po=i; //更新po的位置
        }
        ans += nxt[i];
        if(nxt[i] != len - i) ans++;
    }
    return ans;
}
int main()
{
    //freopen("/Users/zhangkanqi/Desktop/11.txt","r",stdin);
    int t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%s",s);
        printf("%lld\n", solve(s));
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值