LeetCode28. 找出字符串中第一个匹配项的下标(KMP)
题目链接
视频讲解
自己实现
class Solution {
public:
int strStr(string haystack, string needle) {
bool flag = false;
int i = 0, j = 0;
for(int i = 0; i < haystack.size(); i++) {
int j = 0;
for(; j < needle.size(); j++) {
if(haystack[i + j] != needle[j]) break;
}
if(j == needle.size()) return i;
}
return -1;
}
};
题解
class Solution {
public:
int strStr(string haystack, string needle) {
vector<int> next = getNext(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;
}
vector<int> getNext(string needle) {
vector<int> next(needle.size(), 0);
int j = 0;
for(int i = 1; i < needle.size(); i++) {
while(j > 0 && needle[i] != needle[j]) j = next[j - 1];
if(needle[i] == needle[j]) {
j++;
}
next[i] = j;
}
return next;
}
};
总结
LeetCode459. 重复的子字符串
题目链接
视频讲解
题解
class Solution {
public:
bool repeatedSubstringPattern(string s) {
string t = s + s;
t.erase(t.begin());
t.erase(t.end() - 1);
if(t.find(s) == -1) return false;
return true;
}
};
class Solution {
public:
bool repeatedSubstringPattern(string s) {
vector<int> next = getnext(s);
int len = s.size();
if(next[len - 1] != 0 && len % (len - next[len - 1]) == 0) return true;
return false;
}
vector<int> getnext(string s) {
vector<int> next(s.size(), 0);
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;
}
return next;
}
};
总结