您的位置:首页 > 编程语言 > C语言/C++

hiho-1015(c++)

2015-02-04 15:01 141 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: