Problem
http://e-tutor.itsa.org.tw/e-Tutor/mod/programming/view.php?a=1376
Thinking
使用 KMP algo 去算匹配成功的次數, 至於KMP algo是什麼以我的功力目前還沒辦法解釋很清楚, 請google看高手解答
Solution
#include<iostream>
using namespace std;
// KMP algo
void next(string p, int *f){
f[0] = -1;
int j = -1;
for(int i = 1 ; i < p.length() ; i++){
while(j >= 0 && p[j + 1] != p[i])
j = f[j];
if(p[j + 1] == p[i])
j++;
f[i] = j;
}
}
int match(string T,string P, int *f){
int j = -1;
int matchNum = 0;
for(int i = 0 ; i < T.length() ; i++){
while(j >= 0 && P[j + 1] != T[i])
j = f[j];
if(P[j + 1] == T[i])
j++;
if(j == P.length() -1 ){
matchNum++;
j = f[j];
}
}
return matchNum;
}
int main(){
string T,P;
while(cin >> P >> T){
int *f = new int[P.length()];
f[0] = -1;
next(P,f);
cout << match(T, P, f) << endl;
}
}
网友评论