题目:
链接:http://acm.hdu.edu.cn/showproblem.php?pid=2087
题意:
给出字符串s1和s2,找出s1中有多少个s2。
算法:
KMP字符串匹配。
思路:
简单,看代码吧。(需要注意的就是字符串用要scanf输入)
代码:
#include<iostream> #include<cstdio> #include<cstring> using namespace std; char s1[1010],s2[1010]; int next[1010]; int len1,len2,cnt; void get_nextval(char s2[],int len) { int i,j; i = -1; j = 0; next[0] = -1; while(j<len) { if(i == -1 || s2[i] == s1[j]) { ++j; ++i; next[j] = i; } else i = next[i]; } } int KMP(int len1,int len2) { int i,j; i = 0; j = 0; if(len1<len2) return 0; while(i<len1) { if(j == -1 || s1[i] == s2[j]) { i++; j++; if(j == len2) { ++cnt; j = 0; } } else j = next[j]; } return cnt; } int main() { //freopen("input.txt","r",stdin); while(scanf("%s",s1) && s1[0]!=‘#‘) { getchar(); scanf("%s",s2); get_nextval(s2,len2); len1 = strlen(s1); len2 = strlen(s2); cnt = 0; printf("%d\n",KMP(len1,len2)); } return 0; }
原文:http://blog.csdn.net/u013147615/article/details/25062469