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;
}

本文深入探讨了KMP算法的原理与应用,通过代码实例展示了如何高效进行字符串匹配操作。主要内容包括算法介绍、核心思想解析、代码实现及运行结果分析。

1801

被折叠的 条评论
为什么被折叠?



