一、复习与实现KMP算法,要求有运行测试截图。
答:
KMP是实现字符串匹配的较好的算法。本算法的关键在于求出next数组,然后在调用时利用next数组可以使T往后移动得更多,从而提高匹配的效率。
该算法利用C++编程语言实现的代码如下:
//利用C++实现KMP算法 #include <iostream> #include <string> using namespace std; int Index_KMP(string S, string T, int pos, int next[]) { // 利用模式串T的next函数求T在主串S中的第pos个 //字符之后的位置的KMP算法。其中,T非空, // 1≤pos≤StrLength(S) int i = pos; int j = 1; while (i <= S.size() && j <= T.size()) { //0下标存储字符串长度 if (j == 0 || S[i - 1] == T[j - 1]) { ++i; ++j; } // 继续比较后继字符 else j = next[j]; // 模式串向右移动 } if (j > T.size()) return i-T.size(); // 匹配成功 else return 0; } // Index_KMP void get_next(string T, int next[]) { // 求模式串T的next函数值并存入数组next int i = 1; next[1] = 0; int j = 0; while (i < T.size()) { if (j == 0 || T[i - 1] == T[j - 1]) { ++i; ++j; next[i] = j; } else j = next[j]; } } // get_next int main () { int next[100]; string S, T; while(1) { cout << "请输入匹配串:"; cin >> S; /*测试样例:S = "fhwuefihfwabaabcaccaahadc"; S = "fhwuefihfwaba"; T = "abaabcacca"; */ cout << "请输入模式串:"; cin >> T; get_next(T, next); cout << "匹配串为:" << S << endl; cout << "模式串为:" << T << endl; cout << "next数组为:"; for(int i = 1; i <= T.size(); ++i) { cout << next[i] << " "; } cout << endl; if(Index_KMP(S, T, 0, next)) { cout << "匹配成功:匹配串中第" << Index_KMP(S, T, 0, next) << "个字符为模式串开始" << endl; } else{ cout << "匹配失败!未找到模式串!" << endl; } cout << endl; } }
代码运行结果如下:
图 1 KMP算法运行结果示意图