28.找出字符串中第一个匹配项的下标
class Solution {
public:
void getNext(int* next, const string& s) {
int j = 0;
next[0] = 0; // 将前缀表的第一个元素设置为 0
// 注意:下方的 i 从 1 开始
for (int i = 1; i < s.size(); i++) {
// 匹配失败,j 回退
while (j > 0 && s[i] != s[j]) {
j = next[j - 1];
}
// 匹配成功,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; // next 数组记录的起始位置从 0 开始
for (int i = 0; i < haystack.size(); i++) { // i 从 0 开始
while (j > 0 && haystack[i] != needle[j]) {
j = next[j - 1]; // 不匹配,寻找之前匹配的益
}
if (haystack[i] == needle[j]) { // 匹配成功,i j 同时向后移动
j++;
}
if (j == needle.size()) {
// 最长公共前缀后的长度等于 needles.size() 说明出现 haystack 中出现了 needles
return (i - needle.size() + 1);
}
}
return -1;
}
};
459.重复的子字符串
class Solution {
public:
// 获取前缀表
void getNext(int* next, const string& str) {
next[0] = 0;
int j = 0;
for (int i = 1; i < str.size(); i++) {
while (j > 0 && str[i] != str[j]) {
j = next[j - 1];
}
if (str[i] == str[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();
// 数组长度减去最长相同前后缀的长度相当于是第一个周期的长度,也就是一个周期的长度
// 如果这个周期可以被整除,就说明整个数组就是这个周期的循环
// next[len - 1] 表示此时字符串的最长公共前后缀的长度
// (len - (next[len - 1]) 表示 字符串长度 - 最长公共前后缀的长度
if (next[len - 1] != 0 && len % (len - (next[len - 1])) == 0) {
return true;
}
return false;
}
};