28. 实现 strStr()
添加链接描述
这道题啊,直接暴力可以过,但是让我写KMP真的不会
那么写过之后对于KMP有了一些了解(希望不会再忘了),这里是我的理解
- 使用前缀表完成next数组,其中我感觉在s[i]与s[j]不相等的情况下相当于在s作为主串,在s中找模板串
题解和视频:
添加链接描述
class Solution {
public:
void getnext(int* next,string s)
{
int j=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) {
if(needle.size()==0)return 0;
vector<int> next(needle.size());
getnext(&next[0],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;
}
};
459.重复的子字符串
题解和视频:
添加链接描述
class Solution {
public:
void getnext(int* next,string s)
{
int j=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()==1)return false;
vector<int> next(s.size());
getnext(&next[0],s);
int len=s.size();
if(next[len-1]!=0&&len%(len-next[len-1])==0) return true;
else return false;
}
};