您的位置:首页 > 其它

[算法学习笔记]寻找子字符串第一次出现位置

2014-05-27 14:07 232 查看
使用了需要回溯的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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐