您的位置:首页 > 其它

NYOJ5 Binary String Matching ——KMP

2013-06-03 01:38 495 查看
题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=5

题目思路:

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

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
char p[1000], s[1000];
int next[1000];
void getnext() {
int i = 0, j = -1, len = strlen(p);
next[0] = -1;
while (i < len - 1) {
if (j == -1 || p[j] == p[i]) {
j++; i++; next[i] = j;
}
else j = next[j];
}
}
int kmp() {
int i = -1, j = -1, lenp = strlen(p), lens = strlen(s);
getnext();
int num = 0;
while (i < lens) {
if (j == -1 || s[i] == p[j]) {++i; ++j;}
else j = next[j];
if (j == lenp) {i-=j; j = -1; num++;}
}
return num;
}
int main(void) {
int n;
while (~scanf("%d", &n))
while (n--){
scanf("%s%s", p, s);
printf("%d\n", kmp());
}

return 0;
}


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

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

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <cstring>
using namespace std;
string s, p;
int main(void) {
int n;
while (~scanf("%d", &n)) {
while (n--) {
cin >> p >> s;
int num = 0; unsigned ans = 0;
ans = s.find(p, 0);
while (ans != string::npos) {
num++;
ans = s.find(p, ans+1);
}
printf("%d\n", num);
}
}

return 0;
}


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

http://www.cplusplus.com/reference/string/string/find/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: