LeetCode 28. 实现 strStr()
void getnext(string s,int *next){
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) {
if(needle.size()==0)return 0;
vector<int> next(needle.size());
getnext(needle,&next[0]);//将vector型转化为int*型的技巧
int j=0;
for(int i=0;i<haystack.size();i++){
while(j>0 && needle[j]!=haystack[i]){
j=next[j-1];
}
if(haystack[i]==needle[j])j++;
if(j==needle.size())return i-j+1;
}
return -1;
}
这题kmp算法看我笔记。
LeetCode 459.重复的子字符串
class Solution {
public:
void getnext(string s,int *next){
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;
}
}
bool repeatedSubstringPattern(string s) {
if(s.size()==0)return false;
vector<int> next(s.size());
getnext(s,&next[0]);
int len=s.size();
if(next[len-1]!=0 && len%(len-(next[len-1]))==0)return true;//这里加一个next[len-1]!=0条件不太懂
else return false;
}
};
看题解思路,这题比较难。
1118





