28. 找出字符串中第一个匹配项的下标
题目链接: 28. 找出字符串中第一个匹配项的下标
思路: 本题就是KMP的裸题,利用KMP进行匹配,(我习惯next数组从1开始),如果初学者一定要将
- 暴力求解的思路
- KMP的匹配思路
- next数组的更新思路
都自己画图模拟思考,推导一遍,以便加深理解。
我自己用文字很难表述,所以直接为大家献上视频。
4. 帮你把KMP算法学个通透!(理论篇)
5. 帮你把KMP算法学个通透!(求next数组代码篇)
为大家献上我的代码(自己的习惯性写法):
class Solution {
public:
int strStr(string haystack, string needle) {
int m = needle.size();
vector<int> next(m + 1);
haystack = ' ' + haystack, needle = ' ' + needle;
for(int i = 2, j = 0; i < needle.size(); i++){//求next数组
while(j && needle[i] != needle[j + 1]) j = next[j];
if(needle[i] == needle[j + 1]) j++;
next[i] = j;
}
for(int i = 1, j = 0; i < haystack.size(); i++){//KMP匹配过程
while(j && haystack[i] != needle[j + 1]) j = next[j];
if(haystack[i] == needle[j + 1]) j++;
if(j == m) return i - needle.size() + 1;
}
return -1;
}
};
459.重复的子字符串
结论: 求最小周期是KMP的经典应用之一(一定记住)。n - next[n]就是该串的最小周期(前提是该串是重复性的串)。
思路: 直接上视频吧,文字描述太烦了(狗头)
解答链接: LeetCode:459.重复的子字符串
代码1: (在字符匹配环节可以直接调用库函数find(),我是自己写的KMP匹配)
class Solution {
public:
bool repeatedSubstringPattern(string s) {
string temp = s;
string ss = s + s;
ss.erase(ss.begin()); ss.erase(ss.end() - 1);
if(ss == temp) return true;
int n = temp.size();
vector<int> next(n + 1);
temp = ' ' + temp;
for(int i = 2, j = 0; i <= n; i++){
while(j && temp[i] != temp[j + 1]) j = next[j];
if(temp[i] == temp[j + 1]) j++;
next[i] = j;
}
for(int i = 1, j = 0; i <= ss.size(); i++){
while(j && ss[i] != temp[j + 1]) j = next[j];
if(ss[i] == temp[j + 1]) j++;
if(j == n) return true;
}
return false;
}
};
代码2:
class Solution {
public:
bool repeatedSubstringPattern(string s) {
int n = s.size();
s = ' ' + s;
vector<int> next(n + 1);
for(int i = 2, j = 0; i <= n; i++){
while(j && s[i] != s[j + 1]) j = next[j];
if(s[i] == s[j + 1]) j++;
next[i] = j;
}
int t = n - next[n];
return t < n && n % t == 0;
}
};