使用了需要回溯的BF算法和不需要回溯的KMP算法,本文纯属个人学习笔记。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int BF(const char* src, const char* dst);
int KMP(const char* src, const char* dst);
void KMP_next(const char* src, int* next);
int BF(const char* src, const char* dst)
{
int i,j;
i = 0;
int srcLen = strlen(src);
int dstLen = strlen(dst);
while (i < srcLen)
{
j = 0;
while ((src[i] == dst[j]) && (j <dstLen))
{
i++;
j++;
}
if (j == dstLen)
{
return (i - j);
}
i = i - j + 1;
}
return -1;
}
int KMP(const char* src, const char* dst)
{
int next[100];
int i = 0, j = 0;
int srcLen = strlen(src);
int dstLen = strlen(dst);
KMP_next(src, next);
while (i < srcLen)
{
if ((-1 == j) || (src[i] == dst[j]))
{
i++;
j++;
}
else
{
j = next[j];
}
if (j == dstLen)
{
return (i - j);
}
}
return -1;
}
void KMP_next(const char* src, int* next)
{
int j = 0, k = -1;
next[0] = -1;
int srcLen = strlen(src);
while (j < (srcLen - 1))
{
if ((-1 == k) || (src[j] == src[k]))
{
j++;
k++;
next[j] = k;
}
else
{
k = next[k];
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
const char* src = "abcdegfhjfdscdcdhakjgrs";
const char* dst = "cdha";
//int position = BF(src, dst);
int position = KMP(src, dst);
return 0;
}