Skip to content

Instantly share code, notes, and snippets.

Created August 23, 2017 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/a949d6a76f6a72432cfc2c3045e5fb4d to your computer and use it in GitHub Desktop.
Save anonymous/a949d6a76f6a72432cfc2c3045e5fb4d to your computer and use it in GitHub Desktop.
class Solution {
public:
int strStr(string haystack, string needle) {
if (haystack.length() < needle.length()) return -1;
if (needle.length() == 0) return 0;
vector<int> P(needle.length(), -1);
for (int i = 1; i < needle.length(); ++i) {
int j = i;
while (j > 0 && needle[i] != needle[P[j - 1] + 1]) j = P[j - 1] + 1;
if (j > 0) P[i] = P[j - 1] + 1;
}
for (int i = 0, j = 0; i < haystack.length(); ++i) {
while (j > 0 && haystack[i] != needle[j]) j = P[j - 1] + 1;
if (haystack[i] == needle[j]) {
j++;
if (j == needle.length()) return i - j + 1;
}
}
return -1;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment