diff options
| author | Gloria Mundi <gloria@gloria-mundi.eu> | 2024-11-16 01:24:14 +0100 |
|---|---|---|
| committer | Gloria Mundi <gloria@gloria-mundi.eu> | 2024-11-16 01:24:14 +0100 |
| commit | 98567ec798aa8ca2cfbcb85c774dd470f30e30d4 (patch) | |
| tree | 5113d5cc24d1ad5f93810b6442ce584a36950dc8 /content/string/kmp.cpp | |
| parent | ad3856a6b766087df0036de0b556f4700a6498c9 (diff) | |
| parent | 8d11c6c8213f46f0fa19826917c255edd5d43cb1 (diff) | |
mzuenni tests
Diffstat (limited to 'content/string/kmp.cpp')
| -rw-r--r-- | content/string/kmp.cpp | 20 |
1 files changed, 20 insertions, 0 deletions
diff --git a/content/string/kmp.cpp b/content/string/kmp.cpp new file mode 100644 index 0000000..421479e --- /dev/null +++ b/content/string/kmp.cpp @@ -0,0 +1,20 @@ +vector<int> kmpPreprocessing(const string& sub) { + vector<int> b(sz(sub) + 1); + b[0] = -1; + for (int i = 0, j = -1; i < sz(sub);) { + while (j >= 0 && sub[i] != sub[j]) j = b[j]; + b[++i] = ++j; + } + return b; +} +vector<int> kmpSearch(const string& s, const string& sub) { + vector<int> result, pre = kmpPreprocessing(sub); + for (int i = 0, j = 0; i < sz(s);) { + while (j >= 0 && s[i] != sub[j]) j = pre[j]; + i++; j++; + if (j == sz(sub)) { + result.push_back(i - j); + j = pre[j]; + }} + return result; +} |
