演算法: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 ( )//建構函式:建立一個空串
{......餘下全文>>