kmp算法

 1 char a[100],b[100];
 2 int next[100];
 3 void get_next(char b[],int len)
 4 {
 5     next[0]=-1;
 6     int i=0;
 7     int j=-1;
 8     while(i<len)
 9     {
10         if (j==-1||b[i]==b[j])
11         {
12             i++;j++;
13             next[i]=j;
14         }
15         else
16         {
17             j=next[j];
18         }
19     }
20 }
21 int kmpmatch(char a[],char b[])
22 {
23     int alen=strlen(a);
24     int blen=strlen(b);
25     if(blen>alen)
26         return -1;
27     get_next(b,blen);
28     int i=0,j=0;
29     while(i<alen)
30     {
31         if (j==-1||a[i]==b[j])
32         {
33             i++;j++;
34         }
35         else{
36             j=next[j];
37         }
38         if (j==blen)
39         {
40             return i-j;
41         }
42     }
43     return -1;
44 }

 注意  next[0]=-1; 不可用  next[1]=0;     这个是约定的

next[j]=k        代表j 前面 有k个字符串  与开头的字符串的k个是相同的            因为从0开始 所以 接下来比较第k个字符 是否一致,

 

posted on 2014-10-03 18:49  wf110  阅读(202)  评论(0编辑  收藏  举报