Day9 字符串(KMP专题)
LeetCode 28. 找出字符串中第一个匹配项的下标【KMP】
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;
}
}
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;
}
};
LeetCode 459.重复的子字符串【KMP/思维】
用了考验思维的方法。
class Solution {
public:
bool repeatedSubstringPattern(string s) {
return (s+s).find(s,1)!=s.size();
}
};
先把任务完成了,KMP算法相关内容还需要好好学习一下再回来加上。