HDU 2087 剪花布条(模式串在主串中出现的次数主串中子串不可重叠)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2087

题意:求模式串在主串中出现的次数,与模式串匹配的子串之间不可重叠。

思路:用kmp算法解决,在匹配更新结果后,重新定位模式串时,不可用j = next[j],应该直接让j定位到模式串开头。

code:

 1 #include <cstdio>
 2 #include <cstring>
 3 
 4 const int MAXN = 1005;
 5 
 6 char aa[MAXN];
 7 char bb[MAXN];
 8 int next[MAXN];
 9 int lenA, lenB;
10 
11 void GetNext()
12 {
13     int i = 0;
14     int j = -1;
15     next[0] = -1;
16     while (i < lenB)
17     {
18         if (-1 == j || bb[i] == bb[j]) next[++i] = ++j;
19         else j = next[j];
20     }
21 }
22 
23 int KMP()
24 {
25     int i = 0;
26     int j = 0;
27     int ret = 0;
28     while (i < lenA)
29     {
30         if (-1 == j || aa[i] == bb[j])
31         {
32             ++i;
33             ++j;
34             if (j == lenB)
35             {
36                 ++ret;
37                 j = 0;
38             }
39         }
40         else j = next[j];
41     }
42     return ret;
43 }
44 
45 
46 int main()
47 {
48     while (scanf("%s", aa), aa[0] != '#')
49     {
50         scanf("%s", bb);
51         lenA = strlen(aa);
52         lenB = strlen(bb);
53         GetNext();
54         printf("%d\n", KMP());
55     }
56     return 0;
57 }

 

posted @ 2015-07-19 15:43  jasaiq  阅读(303)  评论(0编辑  收藏  举报