Java基礎_方法與陣列
阿新 • • 發佈:2020-12-26
KMP演算法
目錄
一. 應用場景
給定原字串A, 查詢字串A中是否包含字串B. 例如:
在字串A"aassddaassffaa"中查詢是否包含字串B"aassf" ?
二. KMP演算法
核心思想: 略 (去百度,不會寫),不過該演算法很牛啊, 佩服佩服!.
三. 程式碼實現
// 第一步:求模式字串的最長公共前後綴。 void GetPublicPrePostFix(const string& str, vector<int>& output) { output.resize(str.size(), 0); for (size_t i = 1; i < str.size(); ++i) { // 找到那一個可能的最長公共前後綴 int preFixLength = output[i - 1]; while (preFixLength != 0 && str[preFixLength] != str[i]) { preFixLength = output[output[preFixLength - 1]]; } output[i] = preFixLength + (str[preFixLength] == str[i] ? 1 : 0); } } // 第二步:在原字串中查詢是否存在模式串 bool hasSubStr(const string& origin, const string& pattern) { vector<int> table; GetPublicPrePostFix(pattern, table); int index = 0; for (size_t i = 0; i < origin.size(); ++i) { // 找到那個與第i元素相同的下標index, 或者index=0 while (index > 0 && origin[i] != pattern[index]) { index = table[index - 1]; } // 更新index,變成下一輪要對比位置下標。 if (origin[i] == pattern[index]) { index += 1; } if (index == pattern.size()) { return true; } } return false; }