字串 KMP 演算法

來源:互聯網
上載者:User
 

#include <iostream>

 

using namespace std;

 

void fail(string & s, int f[]);

int fastFind(string &src,string &pat,int *fail);

 

/*

fail[i] = k (0<=k<i 且滿足P[0]P[1]……P[k] = P[i-k]P[i-k+1]……P[i] 的最大整數)

         = -1  (others)

*/

 

void fail(string & s, int f[])

{

     int lengthP=s.length();

     f[0]=-1;

     for(int j=1;j<lengthP;j++)

     {

         int i=f[j-1]; // previous value

 

         while(s[j] != s[i + 1] && i > -1)

         {

              i=f[i];

         }

 

         if(s[j]== s[i + 1])

              f[j]=i+1; 

         else

              f[j]=-1;

     }

     cout << endl;

}

 

int fastFind(string &src,string &pat,int *fail)

{

     int posP=0,posT=0;

     int lengthP=pat.length(),lengthT=src.length();

     while(posP<lengthP && posT<lengthT)

     {

         if(pat.at(posP)==src.at(posT))

         {

              posP++;

              posT++;//匹配成功一位就同時向後移一位

         }

         else if(posP==0)

         {

              posT++;//第一個字元都不匹配時,被匹配字串向後移

         }

         else

         {

              posP=fail[posP-1]+1;//否則,通過失效函數找到重新匹配的起始位置

         }

     }

 

     if(posP<lengthP)

     {

         return -1; // Not found

     }

     else

     {

         return posT - lengthP;//匹配成功時返回被匹配串中的匹配上的起始位置

     }

}

 

int main( void )

{

     string src = "aabbaabcaabb";

     string t = "aabc";

     int a[20];

     fail(t, a);

     int pos = fastFind(src, t, a);

     cout << "pos = " << pos << endl;

 

     for(int k = 0; k < t.length(); ++k)

     {

         cout << k << " : " << a[k] << endl;

     }

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.