hdu 2087 剪花布条(KMP算法)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2087

题意

计算字符串 $s$ 中不重叠地包含多少个字符串 $p$ 。

题解

KMP算法的模板题。

代码

#include <bits/stdc++.h>
using namespace std;
const int N = 1010;

int Next[N];
string s, p;

void init_Next() {
    Next[0] =Next[1] = 0;
    for (int i = 1; i < p.size(); i++) {
        int j = Next[i];
        while (j and p[i] != p[j]) j = Next[j];
        Next[i + 1] = (p[i] == p[j] ? j + 1 : 0);
    }
}

void KMP() {
    int ans = 0;
    int last = -1;
    int j = 0;
    for (int i = 0; i < s.size(); i++) {
        while (j and s[i] != p[j]) j = Next[j];
        if (s[i] == p[j]) j++;
        if (j == p.size() and i - last >= p.size()) {
            ++ans;
            last = i;
        }
    }
    cout << ans << "\n";
}

int main() {
    while (cin >> s and s != "#")
        cin >> p, init_Next(), KMP();
}

参考博客

http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html

posted @ 2020-06-02 23:20  Kanoon  阅读(166)  评论(0)    收藏  举报