Last active
September 29, 2015 14:40
-
-
Save timshen91/82f1f1e06dd5fa42d7eb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int Kmp(const std::string& a, const std::string& b) { | |
if (b.empty()) { | |
return 0; | |
} | |
int n = (int)b.size(); | |
std::vector<int> p(n); | |
if (n > 1) { | |
p[1] = 0; | |
} | |
for (int i = 2, j = 0; i < n; i++) { | |
while (b[i-1] != b[j] && j > 0) { | |
j = p[j]; | |
} | |
if (b[i-1] == b[j]) { | |
p[i] = j + 1; | |
} else { | |
p[i] = 0; | |
} | |
j = p[i]; | |
} | |
int i = 0, j = 0; | |
for (; i < (int)a.size() && j < n; i++) { | |
while (a[i] != b[j] && j > 0) { | |
j = p[j]; | |
} | |
if (a[i] == b[j]) { | |
j++; | |
} | |
} | |
if (j == n) { | |
return i - j; | |
} else { | |
return -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment