当前位置: 首页 > news >正文

KMP算法(C++)

       KMP算法与BF算法不一样的在于,当主串与子串不匹配时,主串不回溯,选择了子串回溯,大大提高了运算效率。

       借用了next1【】数组,让子串回溯。get_next函数求next1【】数组,get_next函数的实现难点在于下列几行代码:

while (i < T.length)
    {
        if (j == 0 || T.ch[i] == T.ch[j])
        {
            ++i,  ++j;
            next1[i] = j;
        }
        else
            j = next1[j];
    }

         只要明确两点就容易理解:

1、Tj == Tnext[j],那么next[j+1]的最大值为next[j]+1。

2、Tj != Tnext[j],那么next[j+1]可能的次最大值为next[ next[j] ]+1,以此类推即可求出next[j+1]。

#include<iostream>
#include<string>
using namespace std;
int next1[1000];
typedef struct node
{char ch[251];int length=0;//串当前长度
}SString;
void get_next(SString T)
{int i = 1;//当前串正在匹配字符串位置,也是next数组的索引next1[1] = 0;int j = 0;while (i < T.length){if (j == 0 || T.ch[i] == T.ch[j]){++i;++j;next1[i] = j;}elsej = next1[j];}
}
int Index_KMP(SString S, SString T, int pos)//S主串,T子串,pos从主串pos位置开始匹配
{int i = pos, j = 1;//i为主串下标,j为子串下标while (i <= S.length && j <= T.length){if (S.ch[i] == T.ch[j])//匹配,往下继续{i++;j++;}elsej=next1[j];}if (j >= T.length) return i - T.length;//返回主串与子串匹配时,主串的第一个下标else return 0;
}
int main()
{SString  s;SString  t;cout << "输入主串长度:" ;cin >> s.length;cout << endl;cout << "输入子串长度:";cin >> t.length;cout << endl << "输入主串:";for (int i = 1; i <= s.length; i++)//从下标1开始储存{cin >> s.ch[i];}cout << endl << "输入子串:";for (int i = 1; i <= t.length; i++){cin >> t.ch[i];}get_next(t);int a = Index_KMP(s, t, 1);cout <<endl<< a;
}

http://www.lryc.cn/news/168171.html

相关文章:

  • C++的异常类型与多级catch匹配
  • 查询IP地址可得到哪些信息
  • 考研算法47天:01背包
  • Docker实战技巧(一):Kubernetes基础操作实战
  • android java读写yaml文件
  • 科学计算器网站Desmos网站
  • 结构体-时间的计算
  • pt24django教程
  • Golang开发-new关键字
  • 遗传算法与粒子群算法的Python实现
  • 无涯教程-JavaScript - ASINH函数
  • ActiveMQ面试题(一)
  • node:glob语法以及常用的文件查找库glob、fast-glob
  • 饲料添加剂 微生物 屎肠球菌
  • 二叉搜索树经典笔试题【力扣、牛客】
  • docker系列(1) - docker环境篇
  • web安全漏洞-SQL注入攻击实验
  • 直接插入排序(C++实现)
  • 【k8s】Pod 的钩子
  • MCU软核 3. Xilinx Artix7上运行cortex-m3软核
  • 基于SpringbootShiro实现的CAS单点登录
  • SocketTool V4.0 使用说明
  • Jenkins结合allure生成测试报告
  • 【Linux】缓冲区/回车换行
  • Java手写插入排序和算法案例拓展
  • Python Opencv实践 - 视频文件操作
  • HCS 中的一些概念(二)
  • Scanner类用法(学习笔记)
  • idea2021.1.3版本双击启动,没反应
  • MC-4/11/01/400 ELAU 软件允许用户完全访问相机设置