70,022
社区成员




#include <string>
// 返回模式字符串在源字符串中第一次出现的位置
int KMP0(
char const *szP, // 模式字符串
char const *szS // 源字符串
) ;
int main(int argc, char ** argv)
{
char szP[] = "ababcabcab" ; // 模式字符串
char szS[] = "abababababcabcabcab" ; // 源字符串
int n = KMP0(szP, szS) ;
return 0 ;
}
int KMP0(char const *szP, char const *szS)
{
int nRes = -1 ;
int nLen = strlen(szP) ;
int * parnPS = new int[nLen] ;
parnPS[0] = 0 ;
int nState = 0 ;
int i ;
char c ;
for (i = 0 ; (c = szS[i]) != 0 ; ++ i)
{
for ( ; ; )
{
if (c != szP[nState])
{
if (nState == 0)
break ;
else
nState = parnPS[nState - 1] ;
}
else
{
if (nState > 0)
{
int nPrevState = parnPS[nState - 1] ;
if (c == szP[nPrevState])
parnPS[nState] = nPrevState + 1 ;
else
parnPS[nState] = 0 ;
}
++ nState ;
if (nState == nLen)
{
nRes = i - nLen + 1 ;
goto exit ;
}
break ;
}
}
}
exit:
delete [] parnPS ;
parnPS = NULL ;
return nRes ;
}
//以前写的shift-or, shift-and, kmp算法
template<typename ElemType>
int MatchSO(ElemType* t, int n, ElemType* p, int m, vector<int>& result)
{
typedef unsigned long long NumberType;
const int CharSet = 128;
NumberType B[CharSet];
NumberType D = ~0;
NumberType Check = 1 << (m-1);
NumberType BIT = 1;
for (int i = 0; i < CharSet; ++i) B[i] = ~0;
for (int i = 0; i < m; ++i, BIT <<= 1) B[p[i]] &= ~BIT;
result.clear();
for (int i = 0; i < n; ++i)
{
D = (D << 1) | B[t[i]];
if ((D & Check) == 0) result.push_back(i-m+1);
}
return result.size();
}
template<typename ElemType>
int MatchSA(ElemType* t, int n, ElemType* p, int m, vector<int>& result)
{
typedef unsigned long long NumberType;
const int CharSet = 128;
NumberType B[CharSet];
NumberType D = 0;
NumberType Check = 1 << (m-1);
NumberType BIT = 1;
for (int i = 0; i < CharSet; ++i) B[i] = 0;
for (int i = 0; i < m; ++i, BIT <<= 1) B[p[i]] |= BIT;
result.clear();
for (int i = 0; i < n; ++i)
{
D = ((D << 1) | 1) & B[t[i]];
if ((D & Check) != 0) result.push_back(i-m+1);
}
return result.size();
}
template<typename ElemType>
int MatchKMP(ElemType* t, int n, ElemType* p, int m, vector<int>& result)
{
int * Prefix = new int[m];
{
Prefix[0] = -1;
for (int i = 1, F = -1; i < m; ++i)
{
while (F >= 0 && p[F+1] != p[i]) F = Prefix[F];
if (p[F+1] == p[i]) ++F;
Prefix[i] = F;
}
}
{
result.clear();
for (int i = 0, F = -1; i < n; ++i)
{
while (F >= 0 && p[F+1] != t[i]) F = Prefix[F];
if (p[F+1] == t[i]) ++F;
if (F+1 == m)
{
result.push_back(i-m+1);
F = Prefix[F];
}
}
}
delete[] Prefix;
return result.size();
}