Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/emeraldacoustics/knuth-morris-pratt
An easy-to-use class that implements Knuth-Morris-Pratt algorithm.
https://github.com/emeraldacoustics/knuth-morris-pratt
Last synced: 9 days ago
JSON representation
An easy-to-use class that implements Knuth-Morris-Pratt algorithm.
- Host: GitHub
- URL: https://github.com/emeraldacoustics/knuth-morris-pratt
- Owner: emeraldacoustics
- License: mit
- Created: 2024-04-24T22:23:38.000Z (7 months ago)
- Default Branch: main
- Last Pushed: 2024-04-25T01:44:19.000Z (7 months ago)
- Last Synced: 2024-07-25T02:16:53.728Z (4 months ago)
- Language: C++
- Size: 8.79 KB
- Stars: 7
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# knuth-morris-pratt
An easy-to-use class that implements Knuth-Morris-Pratt algorithm.This class can handle any data types.
For example, `KnuthMorrisPratt KMP;` or `KnuthMorrisPratt KMP;`.`build()` method calculates suffix links for the give array passed as a parameter.
You can easily access suffix link values via the index operator.
Suffix link values are stored in `f`.
If `f[x]` equals `y`, `p[:x]` both begins with and ends with `p[:y]`.Refer example.cpp to see how it works.
```cpp
#include
#include "knuth-morris-pratt-dynamic.hpp"using namespace std;
int main()
{
ios::sync_with_stdio(false);string txt, pat;
cin >> txt >> pat;
/*
* Prepare a vector to be processed by the build method
* This could be a bit annoying for manipulating strings,
* but will prove useful for handling other data types.
*/
vector patv(pat.length(), 0);
for (int i = 0; i < pat.length(); i++)
patv[i] = pat[i];
KnuthMorrisPratt KMP;
KMP.build(patv);vector res;
for (int i = 0, k = 0; i < txt[i]; i++)
{
for (; k > 0 && (k == pat.length() || txt[i] != pat[k]); k = KMP[k]);
if (txt[i] == pat[k])
k++;
// Found a pattern
if (k == pat.length())
res.push_back(i - pat.length() + 1);
}for (const auto & x : res)
cout << x << endl;return 0;
}```