KMP----Next数组

学习笔记

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 
 5 void getNext(const char stringArray[])
 6 {
 7     int next[100];
 8     next[0]=-1;//NEXT数组第一位设为-1; 
 9     int len=strlen(stringArray);
10     
11     int i=0,index=-1;
12     //遍历子串得出NEXT数组 
13     while(i<len)
14     {
15         //当子串没有任何匹配时或者当前字符与前缀字符相同 
16         if(index==-1 ||stringArray[i]==stringArray[index])
17             next[++i]=++index;//得出下一位字符串的权值 
18         else
19             index=next[index];//失配时,前缀回到上一个前缀所保存的权值    
20     }
21     
22     for(int i=0;i<len;i++)    printf("%d ",next[i]);//输出next数组 
23 }
24 
25 int main()
26 {
27     getNext("ababa");
28     
29     return 0;
30 }

 

posted @ 2014-03-25 20:48  随心随想  阅读(172)  评论(0编辑  收藏  举报