目录
题目链接: https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/
题目链接:https://leetcode.cn/problems/repeated-substring-pattern/
题目:28. 找出字符串中第一个匹配项的下标
题目链接: https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
为什么要用KMP?
KMP主要应用在字符串匹配上。KMP的主要思想是当出现字符串不匹配时,可以知道一部分之前已经匹配的文本内容,可以利用这些信息避免从头再去做匹配了。
记录已经匹配的文本内容,是KMP的重点,也是next数组肩负的重任。
前缀表
前缀表:next数组就是一个前缀表,前缀表用来回退,它记录了模式串与主串(文本串)不匹配的时候,模式串应该从哪里开始重新匹配。
eg:要在文本串:aabaabaafa 中查找是否出现过一个模式串:aabaaf。
前缀:是指不包含最后一个字符的所有以第一个字符开头的连续子串。
后缀:是指不包含第一个字符的所有以最后一个字符结尾的连续子串。
最长相等前后缀:
eg:
求前缀表
文本串:aabaabaafa
模式串:aabaaf
求得的最长相等前后缀的长度就是对应前缀表中的元素
可以看出模式串与前缀表对应位置的数字表示的就是:下标i之前(包括i)的字符串中,有多大长度的相同前缀后缀。
前缀表和next数组
- 前缀表直接当作next数组
- 前缀表统一减一
- 前缀表右移一位,初始位置为-1
构造next数组
构造next数组就是计算模式串s的前缀表过程:
步骤:
- 初始化
- 处理前后缀不相同的情况
- 处理前后缀相同的情况
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;
}
};
题目:459.重复的子字符串
题目链接:https://leetcode.cn/problems/repeated-substring-pattern/
给定一个非空的字符串
s
,检查是否可以通过由它的一个子串重复多次构成。
移动匹配的方法:
class Solution {
public:
bool repeatedSubstringPattern(string s) {
string t = s + s;
t.erase(t.begin()); t.erase(t.end() - 1); // 掐头去尾
if (t.find(s) != std::string::npos) return true; // r
return false;
}
};
kmp
前缀表统一减一:
class Solution {
public:
void getNext (int* next, const string& s){
next[0] = -1;
int j = -1;
for(int i = 1;i < s.size(); i++){
while(j >= 0 && s[i] != s[j + 1]) {
j = next[j];
}
if(s[i] == s[j + 1]) {
j++;
}
next[i] = j;
}
}
bool repeatedSubstringPattern (string s) {
if (s.size() == 0) {
return false;
}
int next[s.size()];
getNext(next, s);
int len = s.size();
if (next[len - 1] != -1 && len % (len - (next[len - 1] + 1)) == 0) {
return true;
}
return false;
}
};
前缀表不减一:
class Solution {
public:
void getNext (int* next, const string& s){
next[0] = 0;
int j = 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;
}
}
bool repeatedSubstringPattern (string s) {
if (s.size() == 0) {
return false;
}
int next[s.size()];
getNext(next, s);
int len = s.size();
if (next[len - 1] != 0 && len % (len - (next[len - 1] )) == 0) {
return true;
}
return false;
}
};