summaryrefslogtreecommitdiff
path: root/string
diff options
context:
space:
mode:
authorPaul Jungeblut <s_jungeb@i08pc57.atis-stud.uni-karlsruhe.de>2014-11-22 11:48:51 +0100
committerPaul Jungeblut <s_jungeb@i08pc57.atis-stud.uni-karlsruhe.de>2014-11-22 11:48:51 +0100
commit7130e8263cc88e24e03447b8499db60b2e45e48d (patch)
tree73e0da75a7ffa3379c79ad10168e6b6be828602a /string
parent2ce84beba8d7e2b092720af9c6689b42981c693c (diff)
parentb2859449d6facd0c78f59fd2ce6fdf651b4c8970 (diff)
doofer merge
Merge branch 'master' of https://github.com/pjungeblut/ChaosKITs
Diffstat (limited to 'string')
-rw-r--r--string/kmp.cpp36
1 files changed, 35 insertions, 1 deletions
diff --git a/string/kmp.cpp b/string/kmp.cpp
index 7898192..f7c3630 100644
--- a/string/kmp.cpp
+++ b/string/kmp.cpp
@@ -1 +1,35 @@
-a
+#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;
+}