Template --KMP algorithm

Find about substring

 1 char a[maxn],b[maxn];
 2 int lena,lenb,net[maxn];
 3 void getnet() { ///得到next数组
 4     lenb=strlen(b);
 5     net[0]=-1;
 6     int i=0,j=-1;
 7     while(i<lenb) {
 8         if(j==-1||b[i]==b[j])
 9             net[++i]=++j;
10         else j=net[j];
11     }
12     return ;
 13 is  }
 14  int getans () {   /// the KMP b find the number of occurrences of a string 
15      Lena = strlen (a);
 16      LenB = strlen (b);
 . 17      int ANS = 0 ;
 18 is      IF (= Lena Lena LenB && == = . 1 ) {
 . 19          IF (A [ 0 ] == B [ 0 ]) return  . 1 ;
 20 is          the else  return  0 ;
 21 is      }
 22 is      for ( int I = 0 , J = 0;i<lena;i++) {
23         while(j>0&&a[i]!=b[j]) j=net[j];
24         if(a[i]==b[j]) ++j;
25         if(j==lenb) ans++,j=net[j];
26     }
27     return ans;
28 }
View Code

 

Guess you like

Origin www.cnblogs.com/wuliking/p/11601257.html