数据结构求next、nextval数组算法和KMP算法


求next数组的代码如下:

 1 int get_next(String T,int &next[])
 2 {    //求next数组
 3     int i=1,j=0;
 4     next[1]=0;
 5     while(i<T.length)
 6     {
 7         if(j==0||T.ch[i]==T.ch[j])
 8         {
 9             ++i;++j;
10             next[i]=j;   //若pi=pj,则next[j+1]=next[j]+1
11         }
12         else
13             j=next[j];  //否则令j=next[j],循环继续
14     }
15 }

求nextval数组的代码如下:

 1 int get_nextval(String T,int &nextval[ ]){
 2 //求模式串T的nextval数组。
 3     int i=1,j=0; nextval[1]=0; 
 4     while(i<T.length){
 5         if(j==0||T.ch[i]==T.ch[j]){
 6             ++i;++j;
 7             if (T.ch[i]!=T.ch[j]) nextval[i]=j;
 8             else nextval[i]=nextval[j];
 9         }
10         else j=nextval[j];
11     }    
12 }//get_nextval

kmp算法代码如下:

 1 int Index_KMP(String S,String T,int next[])
 2 {
 3     int i=1,j=1;
 4     while(i<=S.length&&j<=T.length)
 5     {
 6         if(j==0||S.ch[i]==T.ch[j])
 7         {
 8             ++i,++j;   //继续比较后续字符
 9         }
10         else
11             j=next[j];  //模式串右移
12     }
13     if(j>T.length)
14         return i-T.length;   //匹配成功
15     else
16         return 0;   //匹配失败
17 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM