字串匹配 KMP

2021-07-04 15:47:06 字數 742 閱讀 8980

參考:從頭到尾徹底理解kmp

在字串 str 中 匹配模式串 pattern

1. 計算模式串的 next 陣列;

2. 在字串中匹配模式串;當乙個字元匹配時,str[i++], pattern[k++] 繼續匹配下乙個字元;當當前字元不匹配時,根據 next 陣列移動模式字串,k = next[k]

next 陣列:描述模式串中最長相同的字首和字尾的長度。

#include 

using

namespace

std;

class solution else

} else }}

int kmpsearch(string str, string pattern) else

}if (k == pattern.size())

return j-k;

else

return -1;

}solution()

~solution()

private:

int *next;

};int main()

相關:

implement strstr() | 實現字串查詢函式: 用 hash-code 的方法實現字串的搜尋;容易實現,需要支援大數。

字串匹配的boyer-moore演算法:思路簡單,效能更好,但不容易計算得到好字尾表和壞字元表

kmp字串匹配

首先要對模式串進行預處理。預處理過程就是計算出指定位置的字首和字尾的最大相同的長度 啊啊啊啊。估計只有我乙個人能看懂 這個文章說得很清楚 比如說 a a a c b c a a a 0 1 2 0 0 0 1 2 3 void getnext int next,char par 20 int n 翻...

KMP字串匹配

判斷s中是否含有字串t。一般思路為 從s中首字元開始,依次與t中進行比對,直到t結尾或者某乙個位置兩者不同 如果到t的結尾,則表示s中含有t。如果有乙個位置不相同,那麼從s中下乙個字元開始,再次與t中字元比對。如下 i 0,j 0 for i len 這樣的比較,每一次遇到不同的時候都需要從t串的第...

字串匹配 KMP

include include include using namespace std const intmaxn 10005 intf maxn void getf1 string p 可判斷週期及迴圈數 f i 1 p i p j j 1 0 for int i 1 i p.size i cou...