在brute force的字符串匹配中,每次失败后,都要从模式串的第一位开始比较,没有利用到上一次比较中的信息。KMP则是通过对模式串的预处理,匹配过程中,一旦失败,则利用上一次的匹配的结果,不用从模式串的第一位开始比较,从而达到最坏情况下复杂度为线性。
#include<stdio.h>
#define MAX 100
void corresponding(int*,char*);
int index_KMP(char*,char*);
int main()
{
char str_pattern[]="kaka";
char str_src[]="idddddddamkaka";
printf("%d/n",index_KMP(str_src, str_pattern));
getch();
return 0;
}
int index_KMP(char *src,char *pat)
{
int next[MAX],pot=0;
char *base = src,*rear = pat;
corresponding(next,pat);
for(;*src;)
{ pot = src - base;
for(;*pat && *src && *src==*pat;src++,pat++);
if(!*pat)return pot;
if(pat>rear){
pat = rear + next[pat-rear-1];
}
else
{
src++;
pat = rear;
}
}
return -1;
}
void corresponding(int *p,char *ps)
{
int i,k=0;
for(p[0] = 0,i=1;ps[i];p[i] = k= 0,i++)
for(;ps[i] && ps[k]==ps[i];i++,k++)p[i] = k+1;
}
模式匹配算法其实很简单
例如: a b a b c a b
可以这样比较
b a b c a b
a b a b c a b
如果上下完全匹配那就确认了 a b a b c a b 每一个匹配值
a b c a b
a b a b c a b
-----------------------------------------------
b c a b
a b a b c a b
------------------------------------------------
c a b
a b a b c a b
-----------------------------------------------------
a b
a b a b c a b
--------------------------------------------------------
b
a b a b c a b
一次每一个值就会确定
利用这个算法也可以求得 第一个最大重复子串