HDU 4763 Theme Section(KMP)

本文介绍了一种基于KMP算法的字符串匹配方法,该方法能够高效地判断一个字符串中是否存在某个子串,同时该子串也是整个字符串的前缀或后缀。通过分析字符串的next数组并利用KMP算法的核心思想,本文提出了一种新颖的解决方案。

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

解题思路:

只需要判断中间是否存在和前缀后缀相等的字符串即可。

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
#include <set>
using namespace std;
const int maxn = 1000000 + 10;
char s[maxn];
int next[maxn];
void get_next()
{
    int m = strlen(s);
    next[0] = 0; next[1] = 0;
    for(int i=1;i<m;i++)
    {
        int j = next[i];
        while(j && s[i] != s[j]) j = next[j];
        next[i+1] = (s[i] == s[j]) ? j + 1 : 0;
    }
}
bool KMP(char *p, char *t, int n, int m)
{
    int i , j;
    for(i=0,j=0;i<n;i++)
    {
        while(j && t[j] != p[i]) j = next[j];
        if(t[j] == p[i]) j++;
        if(j == m) return 1;
    }
    return 0;
}
int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%s", s);
        get_next();
        int n = strlen(s);
        int j = next[n];
        int ans = 0;
        while(j)
        {
            if(n >= 3 * j && KMP(s+j,s,n-2*j,j))
            {
                ans = j;
                break;
            }
            j = next[j];
        }
        printf("%d\n", ans);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值