20150204
KMP算法
字符串匹配
代码:
#include <iostream>
using namespace std;
string mode;
string source;
int next[10000];
int counts;
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i++){
cin >> mode >> source;
counts = 0;
for(int k = 1; k < mode.length(); k++){
if(mode[k]==mode[counts]){
counts++;
}else{
counts = 0;
if(mode[k]==mode[counts]){
counts++;
}
}
next[k] = counts;
}
counts = 0;
int n = 0;
for(int j = 0; j < source.length(); j++){
if(source[j]==mode[counts]){
counts++;
if(counts == mode.length()){
n++;
counts = next[counts-1];
}
}else{
if(counts == 0)
continue;
j--;
counts = next[counts-1];
}
}
cout << n << endl;
}
return 0;
}