diff --git a/String/knuth_morris_pratt.cpp b/String/knuth_morris_pratt.cpp new file mode 100644 index 000000000..f6f1169d3 --- /dev/null +++ b/String/knuth_morris_pratt.cpp @@ -0,0 +1,64 @@ +/* + The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text + with complexity O(n + m) + 1) Preprocess pattern to identify any suffixes that are identical to prefixes + This tells us where to continue from if we get a mismatch between a character in our pattern + and the text. + 2) Step through the text one character at a time and compare it to a character in the pattern + updating our location within the pattern if necessary +*/ + +#include +#include +#include +using namespace std; +vector getFailureArray(string pattern){ + int pattern_length=pattern.size(); + vectorfailure(pattern_length+1); + failure[0]=-1; + int j=-1; + for(int i=0; ifailure=getFailureArray(pattern); + int k=0; + for(int j=0; j