LeetCode28. 实现 strStr()
经典的KMP算法,理解起来需要费些时间,包含了回溯的思想。先求得next数组之后,当出现不相等情况时,直接跳到next数组值处的下标重新搜索,比起两层for循环大大缩短了时间复杂度,时间复杂度为O(n+m),空间复杂度为O(m)
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[j]!=s[i]){
j=next[j-1];
}
if(s[j]==s[i]){
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;
}
};
LeetCode459.重复的子字符串
KMP方法:
不被最长前后缀包含的必定是最小字串,判断字符串长度是否能被最小字串长度整除,若可以,则该为最小字串,整个字符串均由其构成。
时间复杂度O(n),空间复杂度O(1).
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) {
if(s.size()==0) return false;
int next[s.size()];
getNext(next,s);
if(next[s.size()-1]!=0 && s.size()%(s.size()-next[s.size()-1])==0) return true;
return false;
}
};
移动匹配方法:
将两个字符串拼接,去头去尾后检查原字符串是否在拼接字符串里。
时间复杂度O(n),空间复杂度O(1)
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;
}
};