add trick example of greatest-common-divisor, knuth-morris-pratt, primality-test, quick-pow, split-text

This commit is contained in:
2025-09-23 11:25:26 +08:00
parent 57dd0e9440
commit 5368fcd277
5 changed files with 78 additions and 0 deletions

View File

@@ -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;
}