NYOJ5 Binary String Matching ——KMP
2013-06-03 01:38
495 查看
题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=5
题目思路:
典型的KMP,关键就是修改一下,找到了模式串p之后,继续从大的串s里面模式串开始的位置的下一个位置开始找下一个。
复习了一下KMP,很有意思~
看到了一个STL的方法,碉堡了……
这么短的代码就搞定了……看来STL一定要好好学啊!
http://www.cplusplus.com/reference/string/string/find/
题目思路:
典型的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/
相关文章推荐
- NYOJ-----5---Binary String Matching(KMP)
- nyoj5 Binary String Matching(KMP)
- nyoj -5 Binary String Matching 【kmp】
- nyoj 5 Binary String Matching (KMP)
- NYOJ 5 Binary String Matching (kmp 字符串匹配)
- NYOJ 5 Binary String Matching (kmp 字符串匹配)
- nyoj 5 Binary String Matching(kmp)
- nyoj_5 Binary String Matching
- NYOJ-5 Binary String Matching
- 5 Binary String Matching【kmp】
- nyoj 5 Binary String Matching 【裸kmp】
- nyoj 5 Binary String Matching(string)
- NYOJ 5 Binary String Matching
- NYOJ 5 Binary String Matching
- nyoj5Binary String Matching
- NYOJ 题目5 Binary String Matching
- NYOJ题目5---Binary String Matching
- NYOJ 题目5 Binary String Matching(string类使用)
- Nyoj 5 Binary String Matching
- NYOJ5——Binary String Matching