这道题,也是字符串匹配的问题,数据不大,估计暴力也可以,用时间要求是1000MS,KMP算法15MS过的!给力!
然后唯一不同的是,在模式串中不算有重叠的匹配串,只算一共有多少个不重叠的就好。要想最多,那很好办,只要从头挨着剪,就不会破坏其他的,比如aaaa,aa只要是从剪,就能剪出两个,要是从中间开始,只能剪出一个。
因此……见代码:
#include <cstdio>
#include <cstring>
const int N = 1010;
char str[N], s[N];
int next[N], tl, sl;
void getNext()
{
int j, k;
j = 0, k = next[0] = -1;
while ( j < sl ) {
if ( k == -1 || s[j] == s[k] ) next[++j] = ++k;
else k = next[k];
}
}
int KMP()
{
if ( tl == 1 && sl == 1 )
if ( str[0] == s[0] ) return 1;
else return 0;
int ans = 0, i, j = 0;
getNext();
for ( i = 0; i < tl; ++i ) {
while ( j > 0 && s[j] != str[i] ) j = next[j];
if ( s[j] == str[i] ) j++;
if ( j == sl ) {
ans++;
j = 0;
}
}
return ans;
}
int main()
{
while ( scanf("%s", str) != EOF ) {
if ( str[0] == '#' ) break;
scanf("%s", s);
tl = strlen(str); sl = strlen(s);
printf("%d\n", KMP());
}
}
406

被折叠的 条评论
为什么被折叠?



