28. 实现 strStr()
学习了KMP算法,大为震惊,太妙了,后续再仔细梳理其原理,学完思路后自己写了详细代码如下:
class Solution {
public:
void getNext(vector<int>& next, 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) {
vector<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-j+1;
}
return -1;
}
};
459.重复的子字符串
这道题还得后面再探索****
代码如下:
class Solution {
public:
void getNext(vector<int>& next, 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) {
vector<int> next(s.size());
getNext(next, s);
int i=0;
while(i<s.size()&&next[i]==0) i++;
if(i==s.size()) return false;
else if (s.size()%(s.size()-next[s.size()-1])==0&&next[s.size()-1]!=0) return true;
return false;
}
};