KMP算法
一、传统字符串匹配算法
/* * 从s中第sIndex位置开始匹配p * 若匹配成功,返回s中模式串p的起始index * 若匹配失败,返回-1 */ int index(const std::string &s, const std::string &p, const int sIndex = 0) { int i = sIndex, j = 0; if (s.length() < 1 || p.length() < 1 || sIndex < 0) { return -1; } while (i != s.length() && j != p.length()) { if (s[i] == p[j]) { ++i; ++j; } else { i = i - j + 1; j = 0; } } return j == p.length() ? i - j: -1; }
另外一种简单匹配:
int Index_BF ( char S [ ], char T [ ], int pos ) { /* 若串 S 中从第pos(S 的下标0≤pos<StrLength(S))个字符 起存在和串 T 相同的子串,则称匹配成功,返回第一个 这样的子串在串 S 中的下标,否则返回 -1 */ int i = pos, j = 0; while ( S[i+j] != '