KMP模式匹配考研真題
阿新 • • 發佈:2018-12-10
【2015年計算機聯考真題】
已知字串S="abaabaabacacaabaabcc",模式串t="abaabc"。採用KMP演算法進行匹配,第一次出現失配(s[i] ≠ t[j])時,
i=j=5,則下次開始匹配時,i,j的值分別是()
A. i=1,j=0
B. i=5,j=0
C. i=5,j=2
D. i=6,j=2
【答案】 C
【解析】
KMP演算法主要是求next陣列的過程,首先要理解next陣列是啥
next[i] 代表什麼:
next[i] 代表在模式串t中 長度為i的 字首字尾匹配長度。
下面放上本題KMP演算法程式碼
class Solution { public: int* gen_next(string s) { int *next = new int[s.size()+1]; int i = 1, j = 0; next[0] = next[1] = 0; while (i < s.size()) { while (j>0 && s[i] != s[j]) { //cout << "j=next[" << j << "]" << "=" << next[j]<<" "; j = next[j]; } if (s[i] == s[j]) j++; next[i + 1] = j; //cout << "next[" << i + 1 << "]" << "=" << j << endl; i++; } return next; } int strStr(string haystack, string needle) { if(needle.empty()) return 0; if(haystack.empty()) return -1; int *next = gen_next(needle); int j = 0, i = 0; while (i < haystack.length()) { while (j>0 && haystack[i] != needle[j]) { j = next[j]; } if (haystack[i] == needle[j]) j++; if (j == needle.length()) return i-j+1; i++; } return -1; } };