diff options
| author | pjungeblut <paul.jungeblut@gmail.com> | 2014-11-23 23:01:04 +0100 |
|---|---|---|
| committer | pjungeblut <paul.jungeblut@gmail.com> | 2014-11-23 23:01:04 +0100 |
| commit | 3bf9e44bf552ef5ceef2a4eef87907cc1a8db09b (patch) | |
| tree | 0348c99d32361c5787a41740c0d1f5156a5bd031 /string/kmp.cpp | |
| parent | 4cc304e57566d149582d974cdaf4a7f724c6b5c1 (diff) | |
| parent | 213662f659ed8b0a95da110ae6eb5e91e2ecae71 (diff) | |
gebaut
Diffstat (limited to 'string/kmp.cpp')
| -rw-r--r-- | string/kmp.cpp | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/string/kmp.cpp b/string/kmp.cpp new file mode 100644 index 0000000..f7c3630 --- /dev/null +++ b/string/kmp.cpp @@ -0,0 +1,35 @@ +#include <iostream> +#include <vector> + +using namespace std; + +//Preprocessing Substring sub for KMP-Search +vector<int> kmp_preprocessing(string& sub) { + vector<int> b(sub.size() + 1); + b[0] = -1; + int i = 0, j = -1; + while(i < sub.size()) { + while(j >= 0 && sub[i] != sub[j]) + j = b[j]; + i++; j++; + b[i] = j; + } + return b; +} + +//Searching after Substring sub in s +vector<int> kmp_search(string& s, string& sub) { + vector<int> pre = kmp_preprocessing(sub); + vector<int> result; + int i = 0, j = -1; + while(i < s.size()) { + while(j >= 0 && s[i] != sub[j]) + j = pre[j]; + i++; j++; + if(j == sub.size()) { + result.push_back(i-j); + j = pre[j]; + } + } + return result; +} |
