总结:被KMP的折磨的一天,还是不能很好的理解KMP算法,慢慢来慢慢接触
代码:
class Solution {
public:
void GetNext(int* next,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;
}
return false;
}
};
代码:
class Solution {
public:
void GetNext(int* next,string needle)
{
int j = 0;
next[0] = 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;
}
}
int strStr(string haystack, string needle) {
if(needle.size() == 0)
return 0;
int next[needle.size()];
GetNext(next,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 - needle.size() + 1);
}
return -1;
}
};