刚开始TLE了,是因为找到符合的字符串位置后,j = i+1了...是我蠢了..应该是j = 0;即 模式串向后一模式串个 长度位....
后来 WA...怎么看都没问题...然后发现cnt每次都没初始为0.....
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
using namespace std;
const int N = 1e3+5;
int nxt[N];
int cnt = 0;
char s1[N], s2[N];
void GetNext(char s[], int length)
{
int i=0, j=-1;
nxt[0] = -1;//必须有...
while(i < length){
if(j == -1 || s[i] == s[j]){
i++;
j++;
nxt[i] = j;
}
else j = nxt[j];
}
}
int KMP(char s1[], int n, char s2[], int m)
{
int i = 0, j = 0;
cnt = 0;
while(i < n){
if(j == -1 || s1[i] == s2[j]){
i++;
j++;
}
else
j = nxt[j];
if(j == m){
cnt++;
j = 0;
}
}
return cnt;
}
int main()
{
while(1){
int n, m;
scanf("%s", s1);
if(s1[0] == '#') break;
scanf("%s", s2);
n = strlen(s1);
m = strlen(s2);
GetNext(s2, m);
printf("%d\n", KMP(s1, n, s2, m));
}
return 0;
}