问题描述:
题解:
做法一(kmp模板):
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 9;
char s[N], p[N];
int nex[N];
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
// p: 子串 s:文本串
cin >> p + 1;int m = strlen(p + 1);
cin >> s + 1;int n = strlen(s + 1);
nex[0] = nex[1] = 0;
for(int i = 2,j = 0; i <= m; i++)
{
while(j && p[i] != p[j + 1])j = nex[j];
if(p[i] == p[j + 1])j++;
nex[i] = j;
}
int ans = 0;
for(int i = 1,j = 0; i <= n; i++)
{
while(j && s[i] != p[j + 1])j = nex[j];
if(s[i] == p[j + 1])j++;
if(j == m)ans++;
}
cout << ans << '\n';
return 0;
}
做法二 (字符串hash) :
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 9;
char s[N], p[N];
using ull = unsigned long long;
const ull base = 131;
ull h1[N], h2[N], b[N]; // h1:子串哈希 h2:文本串哈希 b[N]:b的i次方
ull getHash(ull h[], int l, int r) // 获取新的独一的以l开头的r结尾的r的哈希值
{
return h[r] - h[l - 1] * b[r - l + 1];
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
// p: 子串 s:文本串
cin >> p + 1;int m = strlen(p + 1);
cin >> s + 1;int n = strlen(s + 1);
b[0] = 1;
for(int i = 1; i <= n; i++) // 初始化
{
b[i] = b[i - 1] * base;
h1[i] = h1[i - 1] * base + (int)p[i]; // (int)p[i]:第i位的ascii值
h2[i] = h2[i - 1] * base + (int)s[i];
}
int ans = 0;
for(int i = 1; i + m - 1 <= n; i++) // 枚举文本串的子串位置,i+m-1表示以i开头的子串的末尾,子串末尾上限到文本串末尾
{
if(getHash(h1, 1, m) == getHash(h2, i, i+m-1))ans++;
}
cout << ans << '\n';
return 0;
}
知识点:kmp模板,字符串hash