代码随想录算法训练营第九天
一、28. 找出字符串中第一个匹配项的下标
暴力解法:
class Solution {
public:
int strStr(string haystack, string needle) {
if(haystack.size() < needle.size()) return -1;
for(int i = 0; i< haystack.size(); i++){
int temp = i;
if(haystack[i] == needle[0]){
int j = 0;
while( i < haystack.size() && j < needle.size() && haystack[i] == needle[j]){
if(j == needle.size()-1){
return temp;
}
i++;
j++;
}
}
i = temp;
}
return -1;
}
};
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[j] != s[i]) j = next[j-1];
if(s[i] == s[j]){
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
int j = 0;
int next[needle.size()];
getNext(next, needle);
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;
}
};
二、459.重复的子字符串
数组长度减去最长相同前后缀的长度相当于是第一个周期的长度,也就是一个周期的长度,如果这个周期可以被整除,就说明整个数组就是这个周期的循环。
这题首先没有发现这个规律,发现了KMP的next数组从存在不为0的下标之后的值对应都加一这个规律,尝试用一个规律做了一下题解,发现仍然会存在漏洞。
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[j] != s[i]) j = next[j-1];
if(s[i] == s[j]){
j++;
}
next[i] = j;
}
}
bool repeatedSubstringPattern(string s) {
int next[s.size()];
getNext(next, s);
int len = s.size();
if(next[len-1] != 0 && len % (len-next[len-1]) == 0)
return true;
return false;
}
};
文章介绍了两种在字符串中查找指定子串的方法:暴力解法和KMP算法。对于28.找出字符串中第一个匹配项的下标问题,暴力解法通过遍历实现,而KMP算法利用next数组优化了搜索过程。459.重复的子字符串问题则涉及到字符串的周期性质和KMP算法的应用,但作者指出对KMP算法的理解仍有待深入。
614

被折叠的 条评论
为什么被折叠?



