HDU 1686 - Oulipo(kmp)

本文介绍了一种高效的字符串匹配算法——KMP算法,并提供了详细的实现步骤及C语言代码示例。该算法通过预处理模式串生成部分匹配表,避免了传统匹配算法中不必要的回溯,从而提高了搜索效率。

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


分析:

kmp匹配

代码:

#include <cstdio>
#include <cstring>

const int maxn = 1000010;
char w[maxn], t[maxn];
int _next[maxn];

void get_next() 
{
    int w_len = strlen(w);
    int i = 0, j;
    _next[0] = j = -1;
    while (i < w_len) {
        if (j == -1 || w[j] == w[i]) {
            i++;
            j++;
            _next[i] = j;
        } else {
            j = _next[j];
        }
    }
}

int get_times()
{
    int ans = 0;
    int w_len = strlen(w);
    int t_len = strlen(t);
    int i = 0, j = 0;
    while (j < t_len) {
        if (i == -1 || w[i] == t[j]) {
            i++;
            j++;
        } else {
            i = _next[i];
        }
        if (i == w_len) {
            ans++;
            i = _next[i];
        }
    }
    return ans; 
}

int main() 
{
    int T;
    scanf("%d", &T);
    while (T--) {
        memset(w, 0, sizeof(w));
        memset(t, 0, sizeof(t));
        memset(_next, 0, sizeof(_next));
        scanf("%s %s", w, t);
        get_next();
        printf("%d\n", get_times());
    }

    return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值