kmp匹配算法
今天复习了一下kmp匹配算法,做了一下字符串匹配的题和判断字符串是否由子串重复构成的题,加深了印象。
28. 找出字符串中第一个匹配项的下标
class Solution {
public:
void getNext(int* next, string s){
int size = s.size();
int j=0;
next[j] = 0;
for(int i=1; i<size; i++){
while(s[i] != s[j] && j > 0){
j = next[j-1];
}
if(s[i] == s[j]){
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
int size = needle.size();
int next[size];
getNext(next, needle);
int j=0;
for(int i=0; i<haystack.size(); i++){
while(haystack[i] != needle[j] && j>0){
j = next[j-1];
}
if(haystack[i] == needle[j]){
if(++j == size) return i - size + 1;
}
}
return -1;
}
};
class Solution {
public:
int* getNext(string s){
int size = s.size();
int next[size];
int j=0;
next[j] = 0;
for(int i=1; i<size; i++){
while(s[i] != s[j] && j>0){
j = next[j-1];
}
if(s[i] == s[j]){
j++;
}
next[i] = j;
}
return next;
}
bool repeatedSubstringPattern(string s) {
int* next = getNext(s);
int size = s.size();
return size % (size - next[size-1]) == 0 && next[size-1] != 0;
}
};