NYOJ5 Binary String Matching ——KMP

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=5

题目思路:

  典型的KMP,关键就是修改一下,找到了模式串p之后,继续从大的串s里面模式串开始的位置的下一个位置开始找下一个。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <cstring>
 5 using namespace std;
 6 char p[1000], s[1000];
 7 int next[1000];
 8 void getnext() {
 9   int i = 0, j = -1, len = strlen(p);
10   next[0] = -1;
11   while (i < len - 1) {
12     if (j == -1 || p[j] == p[i]) {
13       j++; i++; next[i] = j;
14     }
15     else j = next[j];
16   }
17 }
18 int kmp() {
19   int i = -1, j = -1, lenp = strlen(p), lens = strlen(s);
20   getnext();
21   int num = 0;
22   while (i < lens) {
23     if (j == -1 || s[i] == p[j]) {++i; ++j;}
24     else j = next[j];
25     if (j == lenp) {i-=j; j = -1; num++;}
26   }
27   return num;
28 }
29 int main(void) {
30   int n;
31   while (~scanf("%d", &n)) 
32   while (n--){
33     scanf("%s%s", p, s);
34     printf("%d\n", kmp());
35   }
36 
37   return 0;
38 }

复习了一下KMP,很有意思~

看到了一个STL的方法,碉堡了……

 

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <cstdlib>
 4 #include <algorithm>
 5 #include <cstring>
 6 using namespace std;
 7 string s, p;
 8 int main(void) {
 9   int n;
10   while (~scanf("%d", &n)) {
11     while (n--) {
12       cin >> p >> s;
13       int num = 0; unsigned ans = 0; 
14       ans = s.find(p, 0);
15       while (ans != string::npos) {
16         num++;
17         ans = s.find(p, ans+1);
18       }
19       printf("%d\n", num);
20     }
21   }
22 
23   return 0;
24 }

 

这么短的代码就搞定了……看来STL一定要好好学啊!

http://www.cplusplus.com/reference/string/string/find/

 

 

posted on 2013-06-03 01:38  aries__liu  阅读(697)  评论(0编辑  收藏  举报