add trick example of greatest-common-divisor, knuth-morris-pratt, primality-test, quick-pow, split-text
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
int knuth_morris_pratt(const std::string text, const std::string pattern) {
|
||||
int n = text.length(), m = pattern.length();
|
||||
std::vector<int> next(m, 0);
|
||||
for (int i = 1, j = 0; i < m; i++) {
|
||||
while (j > 0 && pattern[i] != pattern[j]) {
|
||||
j = next[j - 1];
|
||||
}
|
||||
if (pattern[i] == pattern[j]) {
|
||||
j++;
|
||||
}
|
||||
next[i] = j;
|
||||
}
|
||||
|
||||
for (int i = 0, j = 0; i < n; i++) {
|
||||
while (j > 0 && text[i] != pattern[j]) {
|
||||
j = next[j - 1];
|
||||
}
|
||||
if (text[i] == pattern[j]) {
|
||||
j++;
|
||||
}
|
||||
if (j == m) {
|
||||
return i - m + 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
Reference in New Issue
Block a user