演算法:KMP,演算法kmp

來源:互聯網
上載者:User

演算法:KMP,演算法kmp

KMP演算法是一種在目標字串中尋找子串的演算法。


blog宗旨:用圖說話。


KMP演算法 基本思想

(1)求得模式串中每個字元的next[j]值;
(2)進行模式比對。
假設i和j分別為指示主串和模式串中正在比較的字元的當前位置,並對i 和j 賦初值0。在匹配的過程中,若si=tj,則i和j分別增加1,繼續進行比較,否則,i不變,而j退回到next[j]的位置進行新一輪的比較。如此遞推下去,直到出現下列兩種情況:
當j退回到某個值next[j]值時,匹配成功,則i和j分別增加1繼續匹配;
當j退回到值為0時,即next[j]=0,說明主串的當前字元匹配失敗,這時將主串向右滑動一個位置,即從i+1處重新開始新一輪的匹配,此時j=0。
 
KMP匹配演算法

不懂得話,就自己跟上三四遍就好了,代碼附上
有什麼不懂的就問,不過還是盡量自己鑽研的好
#include<iostream.h>
#include<string.h>
#include<stdlib.h>
const int maxLen = 128;
class String
{
int curLen; //串的當前長度
char *ch; //串的儲存數組
public:
String (const String & ob);
String (const char *init);
String ();
~String ()
{
delete [] ch;
}
int Length () const
{
return curLen;
}
String *operator () ( int pos, int len );
int operator == ( const String &ob )const
{
return strcmp (ch, ob.ch) == 0;
}
int operator != ( const String &ob ) const
{
return strcmp (ch, ob.ch) != 0;
}
int operator !() const
{
return curLen == 0;
}
String &operator = (const String &ob);
String &operator += (const String &ob);
char &operator [] (int i);
int fastFind ( String pat ) const;
//void fail (const char *T,int* &f);
void fail (int* &f);
};
String::String ( const String &ob ) //複製建構函式:從已有串ob複製
{
ch = new char[maxLen+1];
if ( !ch )
{
cout << "Allocation Error\n";
exit(1);
}
curLen = ob.curLen;
strcpy ( ch, ob.ch );
}
String::String ( const char *init ) //複製建構函式: 從已有字元數組*init複製
{
ch = new char[maxLen+1];
if ( !ch )
{
cout << "Allocation Error\n";
exit(1);
}
curLen = strlen (init);
strcpy ( ch, init );
}
String::String ( )//建構函式:建立一個空串
{......餘下全文>>
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.