方法:KMP
next数组不减一
class Solution {
private:
void getnext(int* next, const string& s) {
int j = 0;
next[0] = j;
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;
}
}
public:
int strStr(string haystack, string needle) {
int n = haystack.size(), m = needle.size();
int next[m];
getnext(next, needle);
int j = 0;
for (int i = 0; i < n; ++i) {
while (j > 0 && haystack[i] != needle[j]) j = next[j-1];
if (haystack[i] == needle[j]) ++j;
if (j == m) return i - m + 1;
}
return -1;
}
};
next数组统一减一
class Solution {
private:
void getNext(int* next, string& s) {
int j = 0;
next[0] = j;
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;
}
}
public:
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;
}
};
$时间复杂度O(n),空间复杂度O(n)
方法:KMP
class Solution {
private:
void getnext(int* next, const string& s) {
int j = 0;
next[0] = j;
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;
}
}
public:
bool repeatedSubstringPattern(string s) {
int n = s.size();
int next[n];
getnext(next, s);
if (next[n-1] != 0 && n % (n-next[n-1]) == 0) return true;
return false;
}
};
$时间复杂度O(n),空间复杂度O(n)