// KMP.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include <iostream>
#include <new>
using namespace std; /************************************************************************
这个算法的关键在于不用回溯指示主串当前比较位置的变量i,
当主串和模式串失配时,只需要将模式串向右滑动尽可能大的距离
即决定主串当前位置i上的元素 应该和 模式串的哪个元素比较
即关键在于求的一个next[j]数组,当主串在i位置和模式串的j位置失配时,
应该将模式串的next[j]位置元素和主串i位置元素开始比较,重复此过程 所以问题的关键在于求解一个next[j]数组,这个数组的求解是和主串无关的。 ************************************************************************/ //以下代码并没有完全的对参数进行检查 //求解next数组
//lpString为模式串
//next为输入数组
void GetNext(const TCHAR* lpString, int* next)
{
if (NULL == lpString || NULL == next){ return; }
int j = ;
int k = ;
next[] = -;
j = ;
k = -; int length = _tcslen(lpString);
while (j < length - )
{
if (- == k || lpString[j] == lpString[k])
{
++j;
++k;
next[j] = k;
}
else
{
k = next[k];
}
}
} int KMPMatch(const TCHAR* lpMain, const TCHAR* lpMatch)
{
int nMain = _tcslen(lpMain);
int nMatch = _tcslen(lpMatch);
int* pNext = new int[nMatch]();
int i = ;
int j = ; if (NULL == pNext)
{
return -;
} GetNext(lpMatch, pNext);
while (i < nMain && j < nMatch)
{
if (- == j || lpMain[i] == lpMatch[j])
{
++i; ++j;
}
else
{
j = pNext[j];
}
} delete[] pNext;
pNext = NULL; if (j >= nMatch)
{
return i - nMatch;
} return -;
} int _tmain(int argc, _TCHAR* argv[])
{
const TCHAR* lpMain = _T("helloworld");
const TCHAR* lpMatch = _T("oworl"); wcout<<"模式串 "<<lpMatch<<" 在主串 "<<lpMain<<" 中的位置为 " \
<<KMPMatch(lpMain, lpMatch)<<endl;; return ;
}

执行结果如下:

最新文章

  1. php 单双引号的区别
  2. 用xib自定义UITableViewCell
  3. UI设计的重要性--避免二义性的输入提示
  4. HDU 1702 http://acm.hdu.edu.cn/showproblem.php?pid=1702
  5. 常用的富文本框插件FreeTextBox、CuteEditor、CKEditor、FCKEditor、TinyMCE、KindEditor ;和CKEditor实例
  6. 最新版spark1.1.0集群安装配置
  7. [GDI+] 生成缩略图的类文件SmallImage (转载)
  8. apple ID的重要性
  9. ubuntu如何开启SSH服务
  10. Fragment之一:Fragment入门
  11. poj 3897 Maze Stretching 二分+A*搜索
  12. php 四种基础算法 ---- 插入排序法
  13. java 接口的回调
  14. deeplearning.ai 作业中的Python常用命令
  15. C#查询XML解决“需要命名空间管理器”问题
  16. Struts 2 之校验器
  17. 第二十七篇-新建Activity
  18. HAProxy详解(一):HAProxy介绍【转】
  19. ssh: connect to host xx.xx.xxx.xxx port 22: Connection refused
  20. Java学习——多线程例子:李四王五

热门文章

  1. [hackerrank]Closest Number
  2. VirtualUI - Convert your Windows App to HTML5
  3. VS2010/MFC编程入门教程之目录和总结
  4. 58. Length of Last Word
  5. Windows下Java File对象创建文件夹时的一个&quot;坑&quot;
  6. php获取apk包信息的方法
  7. sqlsevrer中output的用法
  8. oracle SQL Develop导出数据库中的表格数据到excel
  9. new int[]和new int()的区别
  10. 转:表单中Readonly和Disabled的区别(HTML中使用javascript解除禁止input输入框代)