求取出现的次数 : 

#include<bits/stdc++.h>
const int maxn = 1e6 + 10;
char mo[maxn], str[maxn];///mo为模式串、str为主串
int next[maxn];
inline void GetNext()
{
    int i = 0, j = -1, len = strlen(mo);
    next[i] = j;
    while(i < len){
//        if(j == -1 || mo[i] == mo[j]) next[++i] = ++j;
//        else j = next[j];
        while( j != -1 && mo[i] != mo[j]) j = next[j];
        next[++i] = ++j;
    }
}
int KmpCount()///计算模式串在子串出现的次数
{
    GetNext();
    int i = 0, j = 0, strL = strlen(str), moL = strlen(mo);
    int ans = 0;
    while(i < strL){
        while( j != -1 && mo[j] != str[i]) j = next[j];
        i++, j++;
        if(j == moL) ans++;
    }
    return ans;///返回模式串在主串中出现的次数(可重叠出现)
}
int main(void)
{
    scanf("%s %s", str, mo);
    printf("%d\n", KmpCount());
    return 0;
}
View Code

相关文章:

  • 2021-10-10
  • 2022-12-23
  • 2021-12-10
  • 2021-12-19
  • 2021-12-23
猜你喜欢
  • 2021-08-20
  • 2021-05-25
  • 2022-03-09
  • 2022-12-23
  • 2021-08-04
  • 2022-02-23
相关资源
相似解决方案