hdu2087

来源:互联网 发布:数据分析的方法和模型 编辑:程序博客网 时间:2024/05/17 02:10

kmp水题。

思路:kmp水过就是了。不过要注意的是不重叠的求。

#include<iostream>#include<cstring>#include<algorithm>#include<cstdio>#define INF 0x3f3f3f3f#define maxn 1000+10using namespace std;char str1[maxn], str2[maxn];int nex[maxn];void get_nex(char *x, int m, int *nex){int i, j;j = nex[0] = -1;i = 0;while (i < m){while (j != -1 && x[j] != x[i]) j = nex[j];nex[++i] = ++j;}}int kmp_count(char *x, int m, char *y, int n){int i, j, ans;i = j = ans = 0;get_nex(x, m, nex);while (i < n){while (j != -1 && y[i] != x[j]) j = nex[j];i++;  j++;if (j >= m){ans++;j = 0;}}return ans;}int main(){while (scanf("%s", str1) != EOF){if (str1[0] == '#') break;scanf("%s", str2);int ans=kmp_count(str2, strlen(str2), str1, strlen(str1));printf("%d\n", ans);}return 0;}


0 0
原创粉丝点击