题目的题意想必大家应该很清楚了!
题目思路:这个题基本上是依据KMP模板打出来的,只需要根据题意来进行修改即可。
代码实现:
#include<iostream>
#include<stdio.h>
#include<cstdio>
#include<string.h>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
char str1[1005];
char str2[1005];
int len1, len2;
int nextt[1005];
void get_next()
{
int i, j;
i = 1;
j = 0;
nextt[1] = 0;
while (i < len1)
{
if (j == 0 || str2[i] == str2[j]) {
i++;
j++;
nextt[i] = j;
}
else
j = nextt[j];
}
}
int KMP()
{
int i = 1, j = 1, cnt = 0;
while (i <= len1)
{
if (j == 0 || str1[i] == str2[j]) {
i++;
j++;
}
else
j = nextt[j];
if (j > len2) {
cnt++;
j = 1;
}//不能是等于,是大于.因为上面是j=1,j++ 等于的时候实际上少了一个
}
return cnt;
}
int main()
{
int i, j, ans;
while (scanf("%s", str1 + 1))
{
if (str1[1] == '#')
return 0;
scanf("%s", str2 + 1);
len1 = strlen(str1 + 1);
len2 = strlen(str2 + 1);
get_next();
ans = KMP();
printf("%d\n", ans);
}
return 0;
}