标签:
算法核心,Next数组(模式串的最长前缀后缀表)。
KMP的思想就是,当匹配不正确时,模式串向后移动的距离为:
已匹配的字符串个数 - next[j]
而Next数组的算法起始也是递归的字符串匹配过程。
Impl:
1 //Next数组计算 2 void CalNext(const char* p, int* next) 3 { 4 int i = 0, j = -1; 5 next[0] = -1; 6 while (p[i] != ‘\0‘) 7 { 8 if (j < 0 || p[i] == p[j]) 9 { 10 i++, j++; 11 next[i] = j; 12 } 13 else 14 j = next[j]; 15 } 16 } 17 18 //利用Next数组的KMP 19 int KMPStr(char* haystack, const char* needle) 20 { 21 int res = 0; 22 int lenS = strlen(haystack); 23 int lenP = strlen(needle); 24 int i = 0, j = 0; 25 int* next = new int[lenP+1]; 26 CalNext(needle, next); 27 28 while (i < lenS && j < lenP) 29 { 30 if (j < 0 || haystack[i] == needle[j]) 31 { 32 i++, j++; 33 } 34 else 35 j = next[j]; 36 37 if (j == lenP) { 38 j = next[j]; 39 res++; 40 } 41 } 42 43 delete[] next; 44 return res; 45 }
标签:
原文地址:http://www.cnblogs.com/sheepsheep/p/4413605.html