如何用cpp实现kmp算法
时间: 2024-05-12 07:17:31 浏览: 59
可以使用以下代码实现KMP算法:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
void getNext(int *next, string pattern){
int j = 0;
next[0] = 0;
for (int i = 1; i < pattern.size(); i++){
while (j > 0 && pattern[i] != pattern[j]){
j = next[j - 1];
}
if (pattern[i] == pattern[j]){
j++;
}
next[i] = j;
}
}
int kmp(string text, string pattern){
int *next = new int[pattern.size()];
getNext(next, pattern);
int j = 0;
for (int i = 0; i < text.size(); i++){
while (j > 0 && text[i] != pattern[j]){
j = next[j - 1];
}
if (text[i] == pattern[j]){
j++;
}
if (j == pattern.size()){
return i - j + 1;
}
}
delete[] next;
return -1;
}
int main(){
string text, pattern;
getline(cin, text);
getline(cin, pattern);
int pos = kmp(text, pattern);
if (pos != -1){
cout << "Pattern found at position " << pos << endl;
}
else{
cout << "Pattern not found" << endl;
}
return 0;
}
```
输入文本和模式,然后使用kmp函数查找模式的位置。如果找到,则输出位置,否则输出“Pattern not found”。
阅读全文