getNext是KMP算法找next的方法,getBetterNext是KMP改进方法。
这个算法的核心想法就是在匹配的时候不走回头路
#include <iostream>#include <vector>#include <string>int IndexKMP(std::string SrcStr, std::string tgtStr, int startIdx);void getNext(std::string tgtStr, std::vector<int>& next);void getBetterNext(std::string tgtStr, std::vector<int>& next);int main(){std::string src = "Haymwanx_wangaAAAAAAAabziteng";std::string tgt = "aAAAAAAAab";std::cout << IndexKMP(src, tgt, 0);}int IndexKMP(std::string SrcStr, std::string tgtStr, int startIdx) {int i = startIdx;int j = 0;std::vector<int> next(255);getNext(tgtStr, next);for (int i = 0; i < next.size(); i++) {std::cout << next[i] << ' ';}std::cout << std::endl;getBetterNext(tgtStr, next);for (int i = 0; i < next.size(); i++) {std::cout << next[i] << ' ';}while (i < SrcStr.size() && j < tgtStr.size()) {if (SrcStr[i] == tgtStr[j]) {++j;++i;}else if (j==0){++i;j = next[j];}else {j = next[j];}}if (j >= tgtStr.size()) {return i - tgtStr.size();}else {return 0;}}void getBetterNext(std::string tgtStr,std::vector<int>& next) {int i = 1, j = 0;next[0] = 0;while (i < tgtStr.size()) {if (j == 0 || tgtStr[i] == tgtStr[j]) {if (tgtStr[i] == tgtStr[j]) {next[i] = next[j];}else {next[i] = j;}++i; ++j;}else {j = next[j];}}}void getNext(std::string tgtStr, std::vector<int>& next) {int i = 1, j = 0;next[0] = 0;while (i < tgtStr.size()) {if (j == 0 || tgtStr[i] == tgtStr[j]) {next[i] = j;++i; ++j;}else {j = next[j];}}}
