28. 实现 strStr()
题目链接/文章讲解/视频讲解:代码随想录
class Solution {
public:
int strStr(string haystack, string needle) {
int j = 0, next[10001] = {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;
}
for(int j = 0, 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 + 1 - needle.size();
}
return -1;
}
};
把视频讲解看完之后自己试着动手实现一下,一定要记住求next数组的那几个步骤。我把求next数组的过程都放在strStr函数当中,其中next数组的创建方式与题解不同,因为needle字符串最大长度是10^4,我直接申请的10001,题解中用的是vector,可以直接用needle的大小来创建数组;还有就是我在最后j的判断原本写的是j == needle.size() - 1,导致测试用例不通过,大家不要犯这样的错误。
459.重复的子字符串
题目链接/文章讲解/视频讲解:代码随想录
class Solution {
public:
bool repeatedSubstringPattern(string s) {
int j = 0, next[10001] = {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 len = s.size();
return len % (len - next[len - 1]) == 0 && next[len - 1] ? true: false;
}
};
还是看完视频讲解后写的,最后要记得判断next[len - 1]是否为0,不然会有用例不通过。