Skip to content

Instantly share code, notes, and snippets.

@YDrall
Created August 18, 2015 16:10
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save YDrall/d782a03430d5002cc3bc to your computer and use it in GitHub Desktop.
Save YDrall/d782a03430d5002cc3bc to your computer and use it in GitHub Desktop.
c++ implementation of kmp string matching algorithm.
#include<iostream>
#include<string>
using namespace std;
int *pre_kmp(string pattern)
{
int size = pattern.size();
int *pie=new int [size];
pie[0] = 0;
int k=0;
for(int i=1;i<size;i++)
{
while(k>0 && pattern[k] != pattern[i] )
{
k=pie[k-1];
}
if( pattern[k] == pattern[i] )
{
k=k+1;
}
pie[i]=k;
}
return pie;
}
void kmp(string text,string pattern)
{
int* pie=pre_kmp(pattern);
int matched_pos=0;
for(int current=0; current< text.length(); current++)
{
while (matched_pos > 0 && pattern[matched_pos] != text[current] )
matched_pos = pie[matched_pos-1];
if(pattern[matched_pos] == text[current])
matched_pos = matched_pos+1;
if( matched_pos == (pattern.length()) )
{
cout<<"Pattern occurs with shift "<< current - (pattern.length() -1 );
matched_pos = pie[matched_pos-1];
}
}
}
int main()
{
string text,pattern;
cout<<"enter text:";
cin>>text;
cout<<"enter pattern:";
cin>>pattern;
kmp(text,pattern);
return 0;
}
@sh-mykola
Copy link

Nice example! Keep it up 👍

@SAKSHAM-SAAM
Copy link

Thank You Sir.

@QuocBao139
Copy link

Thank you very much!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment