poj 3461 (模式串T在主串S中出现的次数)

求模式串在主串中出现的次数
Sample Input

3
BAPC
BAPC
AZA
AZAZAZA
VERDI
AVERDXIVYERDIAN
Sample Output

1
3
0

 

 1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 
 5 const int N = 1000002;
 6 int next[N];
 7 char S[N], T[N];
 8 int slen, tlen;
 9 
10 void getNext()
11 {
12     int j, k;
13     j = 0; k = -1; next[0] = -1;
14     while(j < tlen)
15         if(k == -1 || T[j] == T[k])
16             next[++j] = ++k;
17         else
18             k = next[k];
19 
20 }
21 
22 /*
23 返回模式串在主串S中出现的次数
24 */
25 int KMP_Count()
26 {
27     int ans = 0;
28     int i, j = 0;
29 
30     if(slen == 1 && tlen == 1)
31     {
32         if(S[0] == T[0])
33             return 1;
34         else
35             return 0;
36     }
37     getNext();
38     for(i = 0; i < slen; i++)
39     {
40         while(j > 0 && S[i] != T[j])
41             j = next[j];
42         if(S[i] == T[j])
43             j++;
44         if(j == tlen)
45         {
46             ans++;
47             j = next[j];
48         }
49     }
50     return ans;
51 }
52 int main()
53 {
54     
55     int TT;
56     int i, cc;
57     cin>>TT;
58     while(TT--)
59     {
60         cin>>T>>S;
61         slen = strlen(S);
62         tlen = strlen(T);
63 
64         cout<<KMP_Count()<<endl;
65     }
66     return 0;
67 }
View Code

 

posted @ 2015-05-12 16:45  __Meng  阅读(403)  评论(0编辑  收藏  举报