Title Description
This is a template problem.
Given a string and a string, find the number of occurrences of B in A. A and B are in English characters uppercase or lowercase letters.
B A different positions may overlap occurs.
Input Format
A total of two input lines, respectively, and a string A string B.
Output Format
Output an integer representing the number of occurrences of B in A.
Sample
Sample input
zyzyzyz
zyz
Sample Output
3
Data range and tips
1 <= A, B is the length of <= 10 ~ 6 ~, A, B contains only lowercase letters.
Thinking
Hash value represent a longer string value substring, direct comparison hash values are equal
Code
#include <cstdio>
#include <cstring>
using namespace std;
char a[1000005], b[1000005];
unsigned int sum[1000005], sumb, bt[1000005];
int bs = 37, ans;
int lena, lenb;
unsigned int get(int st) {
return sum[st + lenb - 1] - sum[st - 1] * bt[lenb];
}
int main() {
scanf("%s %s", a + 1, b + 1);
lena = strlen(a + 1), lenb = strlen(b + 1);
bt[0] = 1;
for (int i = 1; i <= lena; ++i) {
sum[i] = sum[i - 1] * bs + a[i];
bt[i] = bt[i - 1] * bs;
}
for (int i = 1; i <= lenb; ++i) {
sumb = sumb * bs + b[i];
}
for (int i = 1; i + lenb - 1 <= lena; ++i) {
if (get(i) == sumb) ans++;
}
printf("%d", ans);
return 0;
}