在没学习kmp之前,如果要在一个串里匹配查找另一个串。可能的实现如下:
#include<stdio.h>
#include<string.h>
int match(const char *W,const char *T)
{
int target_length = strlen(W);
int pattern_length = strlen(T);
int target_index = 0;
int pattern_index = 0;
while (target_index < target_length - pattern_length + 1 && pattern_index < pattern_length){
if (W[target_index] == T[pattern_index]){
++target_index;
++pattern_index;
}
else {
//每次失配T都只移动一个元素
target_index -= (pattern_index - 1);
pattern_index = 0;
}
}
if (pattern_index == pattern_length)
return target_index - pattern_length;
else
return -1;
}
int main()
{
const char *W = "banananobano";
const