Skip to content

Instantly share code, notes, and snippets.

@jizhilong
Created October 4, 2013 10:36
Show Gist options
  • Save jizhilong/6824019 to your computer and use it in GitHub Desktop.
Save jizhilong/6824019 to your computer and use it in GitHub Desktop.
Knuth-Morris-Pratt Algorithm
/*
* =====================================================================================
*
* Filename: kmp.cpp
*
* Description: Knuth-Morris-Pratt Algorithm
*
* Version: 1.0
* Created: 10/04/2013 06:15:30 PM
* Revision: none
* Compiler: gcc
*
* Author: Ji.Zhilong (), zhilongji@gmial.com
* Organization: SJTU
*
* =====================================================================================
*/
#include <vector>
#include <string>
#include <iostream>
using namespace std;
vector<int> kmp(const string &pat, const string &txt)
{
vector<int> skiptable(pat.size(), 0);
for (int i = 1; i < pat.size(); i++)
{
int p = skiptable[i - 1];
while (p != 0 && pat[p] != pat[i])
p = skiptable[p];
if (pat[p] == pat[i])
skiptable[i] = p + 1;
}
vector<int> result;
int p = 0;
for (int i = 0; i < txt.size(); i++)
{
if (txt[i] == pat[p]) {
p += 1;
if (p == pat.size()) {
result.push_back(i - p + 1);
p = skiptable.back();
}}
else {
p = skiptable[p];
}
}
return result;
}
int
main()
{
string pat = "abab";
string txt = "defabababedabab";
vector<int> result = kmp(pat, txt);
for (vector<int>::iterator it=result.begin(); it != result.end(); it++)
cout << *it << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment