【KMP】

#include <iostream>

using namespace std;

const int N = 100010, M = 1000010; // N 为匹串长度, M 为模式串长度

int n, m;
int ne[N];
char p[N], s[M]; // p 为匹配串, s 为模式串 

int main(){
    cin >> n >> p + 1 >> m >> s + 1; // 从下标为1开始
    
    // 求 next[] 数组
    // index 1 2 3
    // value 0 0 1
    for ( int i = 2, j = 0; i <= n; i ++ ) {
        while ( j && p[i] != p[j + 1] ) j = ne[j];
        if ( p[i] == p[j + 1] ) j ++;
        ne[i] = j;
    }

    // KMP 模式匹配
    for ( int i = 1, j = 0; i <= m; i ++ ) {
        while ( j && s[i] != p[j + 1] ) j = ne[j];
        if ( s[i] == p[j + 1] ) j ++;
        if (j == n) {
            cout << i - n << " ";
            j = ne[j];
        }
    }
    
    return 0;
}
/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {

    if ( haystack == "" && needle == ""){
        return 0;
    }

    let len1 = needle.length; // 匹配串长度
    let len2 = haystack.length; // 模式串长度
    const ne = new Array(len1).fill(0);

    // next[] 数组
    for ( let i = 1, j = 0; i < len1; i ++ ) {
        while ( j > 0 && needle[i] !== needle[j] ) j = ne[j - 1];
        if ( needle[i] == needle[j] ) j ++;
        ne[i] = j;
    }

    // KMP
    for ( let i = 0, j  = 0; i < len2; i ++ ) {
        while ( j > 0 && haystack[i] != needle[j]) j = ne[j - 1];
        if ( haystack[i] == needle[j] ) j ++;

        if (j == len1 ){
            return i - len1 + 1;
        }
    }

    return -1;
};

四月份结束会KMP就行,要求不高😓。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值