@[TOC](代码随想录算法训练营第九天| 28. 实现 strStr()、459.重复的子字符串)
28. 实现 strStr()
class Solution {
public:
void getNext(int* next, const string& s) {
next[0] = 0;
for (int i = 1, j = 0; 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);
for (int i = 0, j = 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.重复的子字符串
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;
}
}
bool repeatedSubstringPattern(string s) {
int len = s.size();
if (len == 0)
return false;
int next[len];
getNext(next, s);
return next[len - 1] != 0 && len % (len - next[len - 1]) == 0;
}
};