Day9 28. 实现 strStr() 459.重复的子字符串 字符串总结 双指针回顾
28. 实现 strStr()
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;
}
int next[needle.size()];
getNext(next,needle); //获取next数组,int* next = new int[needle.size()]
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); //needle长度和j相等,所有字符已经找到,退出传递位置Index
}
}
return -1;
}
};
459.重复的子字符串
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;
}
}
bool repeatedSubstringPattern(string s) {
if (s.size() == 0) {
return false;
}
int next[s.size()];
getNext(next, s);
int len = s.size();
if (next[len - 1] != 0 && len % (len - (next[len - 1] )) == 0) {
return true;
}
/*
*假设字符串s使用多个重复子串构成(这个子串是最小重复单位),重复出现的子字符串长度是x,所以s是由n * x组成。
*因为字符串s的最长相同前后缀的长度一定是不包含s本身,所以 最长相同前后缀长度必然是m * x,而且 n - m = 1,
*所以如果 nx % (n - m)x = 0,就可以判定有重复出现的子字符串。
*next 数组记录的就是最长相同前后缀,如果 next[len - 1] !=0,则说明字符串有最长相同的前后缀(就是字符串里的前缀子串和后缀子串相同的最长长度)。
*最长相等前后缀的长度为:next[len - 1] + 1。(这里的next数组是以统一减一的方式计算的,因此需要+1
*/
return false;
}
};
字符串总结
链接
双指针回顾
链接