Pattern matching kmp algorithm (c++)

After gnawing for two days, I finally took down the kmp.
Alas, the data structure class did not listen well

void getnext(int next[],string t)
{
    
    
   int j=0,k=-1;
   next[0]=-1;
   while(j<t.length()-1)
   {
    
    
      if(k == -1 || t[j] == t[k])
      {
    
    
         j++;k++;
         if(t[j]==t[k])//当两个字符相同时,就跳过
            next[j] = next[k];
         else
            next[j] = k;
      }
      else k = next[k];         // k回溯到当前指针的前一个位置也就是第k个元素在失配时,子串的第next[k]个元素与当前母串的位置进行匹配
   }
}
int kmp(string s,string t)
{
    
    
   int next[maxsize],i=0,j=0;
   getnext(next,t);
   while(i<s.length()&&j<t.length())
   {
    
    
      if(j==-1 || s[i]==t[j])
      {
    
    
         i++;
         j++;
      }
      else 
      	j=next[j];               
   }
   if(j>=t.length())
       return (i-t.length());         //匹配成功,返回子串的位置
   else
      return -1;                  //没找到
}

Guess you like

Origin blog.csdn.net/qq_43477024/article/details/109691062
Recommended