TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
knuth_morris_pratt.cpp File Reference

The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text with complexity O(n + m) More...

#include <cassert>
#include <iostream>
#include <string>
#include <vector>
Include dependency graph for knuth_morris_pratt.cpp:

Go to the source code of this file.

Namespaces

namespace  string_search
 

Functions

std::vector< size_t > string_search::getFailureArray (const std::string &pattern)
 Generate the partial match table aka failure function for a pattern to search.
 
size_t string_search::kmp (const std::string &pattern, const std::string &text)
 KMP algorithm to find a pattern in a text.
 
static void tests ()
 self-test implementations
 
int main ()
 

Detailed Description

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
    Author
    Yancey

Definition in file knuth_morris_pratt.cpp.

Function Documentation

◆ main()

int main ( void )

Definition at line 95 of file knuth_morris_pratt.cpp.

95 {
96 tests();
97 return 0;
98}
static void tests()
self-test implementations

◆ tests()

static void tests ( )
static

self-test implementations

Returns
void

Definition at line 79 of file knuth_morris_pratt.cpp.

79 {
80 assert(kmp("abc1abc12l", "alskfjaldsabc1abc1abc12k2") == std::string::npos);
81 assert(kmp("bca", "abcabc") == 1);
82 assert(kmp("World", "helloWorld") == 5);
83 assert(kmp("c++", "his_is_c++") == 7);
84 assert(kmp("happy", "happy_coding") == 0);
85 assert(kmp("", "pattern is empty") == 0);
86
87 // this lets the user know that the tests have passed
88 std::cout << "All KMP algorithm tests have successfully passed!\n";
89}