作用
- KMP主要应用在字符串匹配上。
思想
- KMP的主要思想是当出现字符串不匹配时,可以知道一部分之前已经匹配的文本内容,可以利用这些信息避免从头再去做匹配了。
- 如何记录已经匹配的文本内容,是KMP的重点,也是next数组肩负的重任。
前缀表
前缀表是用来回退的,它记录了模式串与主串(文本串)不匹配的时候,模式串应该从哪里开始重新匹配。
注意:
- 如果前缀表中下标不统一减一,则回跳时需看上一个位置的记录
- 如果前缀表整体右移一位,且0位置初始化为-1,则回跳时就看本位置的记录
next数组的实现:1.初始化;2.前后缀不相同;3.前后缀相同;next
// j指向前缀末尾位置,同时表示i及其之前的最长前缀的长度; i指向后缀末尾位置// *******************************************************************// 初始化next[0] = -1; j = -1;// *******************************************************************// 前后缀不相同while (j >= 0 && s[i] != s[j + 1]) {j = next[j]; // 向前回退}// *******************************************************************// 找到相同的前后缀if (s[i] == s[j + 1]) {j++;}next[i] = j;// *******************************************************************// 整体代码void getNext(int* next, const string& s){int j = -1;next[0] = j;for(int i = 1; i < s.size(); i++) { // 注意i从1开始while (j >= 0 && s[i] != s[j + 1]) { // 前后缀不相同了j = next[j]; // 向前回退}if (s[i] == s[j + 1]) { // 找到相同的前后缀j++;}next[i] = j; // 将j(前缀的长度)赋给next[i]}}
建立next数组


整体减一后的next数组

例题:28. 实现 strStr()
// 前缀表统一减一class Solution {public:void getNext(int* next, const string& s) {int j = -1;next[0] = j;for(int i = 1; i < s.size(); i++) { // 注意i从1开始while (j >= 0 && s[i] != s[j + 1]) { // 前后缀不相同了j = next[j]; // 向前回退}if (s[i] == s[j + 1]) { // 找到相同的前后缀j++;}next[i] = j; // 将j(前缀的长度)赋给next[i]}}int strStr(string haystack, string needle) {if (needle.size() == 0) {return 0;}int next[needle.size()];getNext(next, needle);int j = -1; // // 因为next数组里记录的起始位置为-1for (int i = 0; i < haystack.size(); i++) { // 注意i就从0开始while(j >= 0 && haystack[i] != needle[j + 1]) { // 不匹配j = next[j]; // j 寻找之前匹配的位置}if (haystack[i] == needle[j + 1]) { // 匹配,j和i同时向后移动j++; // i的增加在for循环里}if (j == (needle.size() - 1) ) { // 文本串s里出现了模式串treturn (i - needle.size() + 1);}}return -1;}};
// 前缀表(不减一)class Solution {public:void getNext(int* next, const string& s) {int j = 0;next[0] = 0;for(int i = 1; i < s.size(); i++) {while (j > 0 && s[i] != s[j]) {j = next[j - 1];}if (s[i] == s[j]) {j++;}next[i] = j;}}int strStr(string haystack, string needle) {if (needle.size() == 0) {return 0;}int next[needle.size()];getNext(next, needle);int j = 0;for (int i = 0; i < haystack.size(); i++) {while(j > 0 && haystack[i] != needle[j]) {j = next[j - 1];}if (haystack[i] == needle[j]) {j++;}if (j == needle.size() ) {return (i - needle.size() + 1);}}return -1;}};
