class Solution {
//kmp O(n+m)
//1. search part:
//needle[j] != neddle[i], then get j = next[j], do not let i decrease at any time
//2. generate jump table of needle:
//get next array by matching needle string and needle+1 string
//two special state of next array, next[0] = -1 and next[1] = 0
public:
void generate_kmp_table(char* needle, vector<int>& next)
{//模式字符串与自身错位匹配,得到next
int len = strlen(needle);
if(0 == len) return;
next.resize(len);
int i = 0;
int j = -1;
next[0] = -1;
while(i < len-1)
{
if(j == -1 || needle[i] == needle[j])
{
i++;
j++;
next[i] = j;
}
else j = next[j];
}
}
char *strStr(char *haystack, char *needle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len1 = strlen(haystack);
int len2 = strlen(needle);
vector<int> next;
generate_kmp_table(needle, next);
//search
int i = 0;
int j = 0;
while(i < len1 && j < len2)
{
if(j == -1 || haystack[i] == needle[j])
{
i++;
j++;
}
else j = next[j];
}
if(j == len2) return &haystack[i-j];
else return NULL;
}
};
second time
class Solution {
public:
void getJumpTable(char* str, vector<int>& jump)
{
int len = strlen(str);
if(len == 0) return;
jump.resize(len, 0);
int i = 0;
int j = -1;
jump[0] = -1;
while(i < len-1)
{
if(j == -1 || str[i] == str[j])
{
i++;
j++;
jump[i] = j;
}
else j = jump[j];
}
}
char *strStr(char *haystack, char *needle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len1 = strlen(haystack);
int len2 = strlen(needle);
//if(len1 == 0 || len2 == 0) return NULL;
vector<int> jump;
getJumpTable(needle, jump);
int i = 0;
int j = 0;
while(i < len1 && j < len2)
{
if(j == -1 || haystack[i] == needle[j])
{
i++;
j++;
}
else j = jump[j];
}
if(j == len2) return &haystack[i-len2];
else return NULL;
}
};