1. 程式人生 > 實用技巧 >Oulipo(KMP) POJ - 3461

Oulipo(KMP) POJ - 3461

給出n對字串,p,s;想要知道p在s中出現了幾次。


#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstring>
#include<stdio.h>
#include<algorithm>
#include<map>
#include<queue>
#include<set>
#include <sstream>
#include<vector>
#include<cmath>    
#include
<stack> #include<time.h> #include<ctime> using namespace std; #define inf 1<<30 #define eps 1e-7 #define LD long double #define LL long long #define maxn 1000005 int Next[maxn] = {}; void GetNext(string s)//套上模板 { int i = 0; int j = -1; int len = s.length(); Next[0] = -1
; while (i < len) { if (j == -1 || s[i] == s[j]) { i++; j++; Next[i] = j; } else { j = Next[j]; } } } int Kmp(string p, string s) { GetNext(s);//找出s的next陣列 int i = 0; int j = 0;
int len1 = p.length(); int len2 = s.length(); int sum = 0; while (i < len1) { if (j == -1 || p[i] == s[j]) { i++; j++; } else { j = Next[j]; } if (j == len2)//找到一個 { sum++;//加一 j = Next[j]; } } return sum; } int main() { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) { string s, p; cin >> s >> p; printf("%d\n", Kmp(p, s)); } }