// 计算部分匹配表(前缀表) voidcomputePrefixFunction(constchar* pattern, int m, int* prefix){ int k = 0; prefix[0] = 0; for (int i = 1; i < m; ++i) { while (k > 0 && pattern[k] != pattern[i]) { k = prefix[k - 1]; } if (pattern[k] == pattern[i]) { ++k; } prefix[i] = k; } }
// KMP 主算法,返回匹配的起始位置 voidkmpSearch(constchar* text, constchar* pattern, int* matches, int& match_count){ int n = strlen(text); int m = strlen(pattern); int prefix[m]; computePrefixFunction(pattern, m, prefix);
int q = 0; match_count = 0; for (int i = 0; i < n; ++i) { while (q > 0 && pattern[q] != text[i]) { q = prefix[q - 1]; } if (pattern[q] == text[i]) { ++q; } if (q == m) { matches[match_count++] = i - m + 1; q = prefix[q - 1]; } } }
intmain(){ constchar* text = "ABABDABACDABABCABAB"; constchar* pattern = "ABABCABAB"; int matches[100]; int match_count; kmpSearch(text, pattern, matches, match_count); if (match_count == 0) { cout << "未找到匹配" << endl; } else { cout << "匹配位置:"; for (int i = 0; i < match_count; ++i) { cout << matches[i] << " "; } cout << endl; } return0; }
My personal blog is a lively corner where I document my journey of self-improvement, continuous learning, and share the highs and lows of my life's adventures. It's a digital diary where I enthusiastically capture the steps I take to better myself, the invaluable lessons I've learned, and a platform to express my thoughts and experiences.