class Solution {
public:
vector<int> getNext(string needle) {
vector<int> next(needle.size(), 0);
int j = 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;
}
return next;
}
int strStr(string haystack, string needle) {
int m = haystack.size();
int n = needle.size();
int j = 0, i = 0;
vector<int> next = getNext(needle);
while(i < m) {
while(j > 0 && haystack[i] != needle[j]) {
j = next[j - 1];
}
if(haystack[i] == needle[j]) {
j++;
}
i++;
if(j == n) return i - j;
}
return -1;
}
};