#ifndef _KMP_H_
#define _KMP_H_
template<typename T>
void prefix(T* p, int m, int* next)
{
int k = -1;
for(int i=0; i<m; i++)
{
while(k>-1 && p[i]!=p[k])
k=next[k];
if(p[i]==p[k+1])
next[i]=k+1;
else
next[i]=0;
}
}
template<typename T>
int KMP(T* t, int n, T* p, int m, int* out)
{
int c=0;
int q=-1;
int next[m];
// the memset can't use there
for(int i=0; i<m; next[i++]=0);
for(int i=0; i<n-m; out[i++]=0);
prefix(p, m, next);
for(int i=0; i<n; i++)
{
if(q>-1 && p[q+1]!=t[i])
q=next[q];
if(p[q+1]==t[i])
q++;
if(q==m-1)
{
out[c++]=i-m+1;
q=next[q];
}
}
return c;
}
#endif //_KMP_H_
#define _KMP_H_
template<typename T>
void prefix(T* p, int m, int* next)
{
int k = -1;
for(int i=0; i<m; i++)
{
while(k>-1 && p[i]!=p[k])
k=next[k];
if(p[i]==p[k+1])
next[i]=k+1;
else
next[i]=0;
}
}
template<typename T>
int KMP(T* t, int n, T* p, int m, int* out)
{
int c=0;
int q=-1;
int next[m];
// the memset can't use there
for(int i=0; i<m; next[i++]=0);
for(int i=0; i<n-m; out[i++]=0);
prefix(p, m, next);
for(int i=0; i<n; i++)
{
if(q>-1 && p[q+1]!=t[i])
q=next[q];
if(p[q+1]==t[i])
q++;
if(q==m-1)
{
out[c++]=i-m+1;
q=next[q];
}
}
return c;
}
#endif //_KMP_H_