dsalglib  1.0.0
dsalglib is a ready to use data structures and algorithms library written in C++ . Object Oriented Template implementations are written.
kmpsearch.h
Go to the documentation of this file.
1 //
2 // Created by moghya_s on 12/26/2016.
3 //
4 
5 #ifndef DSALGLIB_KMPSEARCH_H
6 #define DSALGLIB_KMPSEARCH_H
7 
8 #include "array.h"
9 
10 namespace dsa
11 {
12  template<typename type>
14 
15  long long int pindex =0;
16  for(long long int cindex=1; cindex < pat.size();)
17  {
18  if(pat[cindex] == pat[pindex]){
19  pre[cindex] = pindex + 1;
20  pindex++;
21  cindex++;
22  }else{
23  if(pindex != 0){
24  pindex = pre[pindex-1];
25  }else{
26  pre[cindex] = 0;
27  cindex++;
28  }
29  }
30  }
31  }
32 
33  template<typename type>
35  {
36  array<long long int> pre(pat.size(),0),res;
37  kmppreprocess(pre,pat);
38 
39  long long int aindex=0,pindex=0;
40  while(aindex<arr.size())
41  {
42  if(arr[aindex]==pat[pindex]){
43  aindex++; pindex++;
44  }
45 
46  if(pindex==pat.size()){
47  res.push_back(aindex-pindex);
48  pindex=pre[pindex-1];
49  }else if(aindex<arr.size() && arr[aindex]!=pat[pindex]){
50  if(pindex!=0) pindex= pre[pindex-1]; else aindex++;
51  }
52  }
53  return res;
54  }
55 }
56 #endif //DSALGLIB_KMPSEARCH_H
Definition: alginc.h:12
array< long long int > kmpsearch(array< type > arr, array< type > pat)
Definition: kmpsearch.h:34
long long int size()
Definition: array.h:98
void kmppreprocess(array< long long int > pre, array< type > pat)
Definition: kmpsearch.h:13