给定一个文本串 text 和一个模式串 pattern,然后判断模式串 pattern 是否是文本串 text 的子串
KMP算法复杂度是O(n + m)
#include <bits/stdc++.h>
using namespace std;
int next[105];
void getNext(char s[], int len){
int j = -1;
next[0] = -1;
for(int i = 1; i < len; i++){
while(j != -1 && s[i] != s[j+1]){
j = next[j];
}
if(s[i] == s[j+1]){
j++;
}
//next[i] = j;
if(j == -1 || s[i+1] != s[i+1]){
next[i] = j;
}else{
next[i] = next[j];
}
}
}
bool KMP(char text[], char pattern[]){
int n = strlen(text), m = strlen(pattern);
getNext(pattern, m);
int j = -1;
for(int i = 0; i < n; i++){
while(j != -1 && text[i] != pattern[j+1]){
j = next[j];
}
if(text[i] == pattern[j+1]){
j++;
}
if(j == m - 1){
return true;
}
}
return false;
}
int main(){
cout << KMP("abababab", "aba"); // true
return 0;
}