题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2087
kmp模板题:
#include <cstdio> #include <cstring> #include <iostream> using namespace std; #define N 1100 char s1[N], s2[N]; int p[N], L1, L2; void Getp() { int i=0, j=-1; p[0] = -1; while(i<L2) { if(j==-1 || s2[i]==s2[j]) { i++;j++; p[i] = j; } else j = p[j]; } } int kmp() { int i=0, j=0, ans = 0; while(i<L1) { if(j==-1 || s1[i] == s2[j]) { i++; j++; } else { j = p[j]; } if(j==L2) { ans++; j=0; } } return ans; } int main() { while(scanf("%s%s", s1, s2), strcmp(s1, "#")) { L1 = strlen(s1); L2 = strlen(s2); Getp(); int ans = kmp(); printf("%d ", ans); } return 0; }
#include<iostream> #include<stdio.h> #include<algorithm> #include<string.h> #define N 2100 using namespace std; int main() { char s1[N],s2[N]; int len1,len2,i,j,ans; while(scanf("%s",s1),strcmp(s1,"#")) { scanf("%s",s2); len2=strlen(s2); len1=strlen(s1); if(len1<len2) { printf("0 "); continue; } else { ans=0; i=j=0; while(1) { if(s1[i]!=s2[j]) i++; while(s1[i]==s2[j]&&j<len2&&i<len1) { i++; j++; } if(j==len2) ans++; if(i==len1) break; j=0; } printf("%d ",ans); } } return 0; }