light oj 1255 - Substring Frequency (KMP)

简介: 输入两个字符串,计算二串在一串中出现的次数。 裸裸的KMP,参考刘汝佳《算法竞赛入门经典训练指南》 P212 或数据结构。

题目链接

题意:

     输入两个字符串,计算二串在一串中出现的次数。

     裸裸的KMP,参考刘汝佳《算法竞赛入门经典训练指南》 P212 或数据结构。

代码如下:

//light oj 1255 - Substring Frequency (KMP)
//2013-05-13-19.12
#include <stdio.h>
#include <string.h>
const int maxn = 1000006;
char a[maxn];
char b[maxn];
int f[maxn];
void getfail()
{
    int l = strlen(b);
    f[0] = 0;
    f[1] = 0;
    for (int i = 1; i < l; i++)
    {
        int j = f[i];
        while (j && b[i] != b[j])
            j = f[j];
        if (b[i] == b[j])
            f[i+1] = j+1;
        else
            f[i+1] = 0;
    }
}
int kmp()
{
    int ans = 0;
    int la = strlen(a);
    int lb = strlen(b);
    getfail();
    int j = 0;
    for (int i = 0; i < la; i++)
    {
        while (j && a[i] != b[j])
            j = f[j];
        if (b[j] == a[i])
            j++;
        if (j == lb)
            ans++;
    }
    return ans;
}
int main()
{
    int t;
    scanf("%d", &t);
    for (int i = 1; i <= t; i++)
    {
        scanf("%s %s", a, b);
        printf("Case %d: %d\n", i, kmp());
    }
    return 0;
}
目录
相关文章
light oj 1159 - Batman LCS
学过简单动态规划的人应该对最长公共子序列的问题很熟悉了,这道题只不过多加了一条字符串变成三条了,还记得,只要把状态变成三维的即可。
39 0
|
人工智能
UPC-Match Matching(完全背包dp+字符串)
UPC-Match Matching(完全背包dp+字符串)
84 0
HDOJ/HDU 1062 Text Reverse(字符串翻转~)
HDOJ/HDU 1062 Text Reverse(字符串翻转~)
120 0
|
机器学习/深度学习 存储 人工智能
|
Java
HDU 1711 Number Sequence(KMP裸题,板子题,有坑点)
Number Sequence Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 27028    Accepted Submission...
1029 0
[LeetCode]--71. Simplify Path
Given an absolute path for a file (Unix-style), simplify it. For example, path = “/home/”, =&gt; “/home” path = “/a/./b/../../c/”, =&gt; “/c” click to show corner cases. Corner Cases:
1068 0
[LeetCode]--29. Divide Two Integers
Divide two integers without using multiplication, division and mod operator. If it is overflow, return MAX_INT. 以前我记得做过乘法变加法吧,这个有点像除法变减法,用位运算,二进制嘛,左移一位相当于乘以二。 一个有趣的是 Math.abs(-2147483648
1133 0
[LeetCode]--5. Longest Palindromic Substring
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. 我用的是中心扩展法 因为
1233 0