strstr能在日常满足大部分的字符串搜索需求,但面对更高性能要求,其只能让位于新的算法,这些新的算法能将复杂度降为O(n)。
首先,介绍状态机算法。
这个算法的核心是构造一个搜索串的状态机,当输入逐个字符输入的时候,状态机运行。当状态机运行到最后一个状态的时候,也就是实现了一次匹配。此算法的核心是状态机的构造。构造复杂度最高为O(m^2)。所以此算法的复杂度最高为O(n+m^2)。
还有一种KMP算法,记录每个位置匹配失败时搜索串回退的位置。逐个字符进行匹配搜索时,若匹配失败,则将搜索串的指针回退,继续进行匹配搜索。
#include<iostream>
using namespace std;
const int m = 10;
int b[m+1] = { 0 };
void compute_prefix(char* s){
b[1] = 0;
int p = 0;
for (int i = 2; i <= m; i++){
while (p != 0 && s[i-1] != s[p]){
p = b[p];
}
if (s[i-1] == s[p]){
p++;
}
b[i] = p;
}
}
void kmp(char *s, char *T){
int n = strlen(T);
int p = 0;
for (int i = 1; i <= n; i++){
while (p > 0 && T[i-1] != s[p]){
p = b[p];
}
if (T[i-1] == s[p]){
p++;
}
if (p == m){
printf("%d\n", i);
p = b[p];
}
}
}
void main(){
char str[] = "ababababca";
char T[] = "ababbababababcaca";
compute_prefix(str);
kmp(str, T);
}