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、T j == Tnext[j],那么next[j+1]的最大值为next[j]+1。

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

cpp 复制代码
#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;
		}
		else
			j = 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++;
		}
		else
			j=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;
}
相关推荐
大白的编程日记.1 小时前
【C++笔记】C++编译器拷贝优化和内存管理
java·开发语言·c++·笔记
CrazyZ1262 小时前
c++primer第九章内存模型和名称空间学习笔记
c++·笔记·学习
小灰灰爱代码3 小时前
C++——将数组a[5]={-1,2,9,-5,7}中小于0的元素置成0。并将其结果输出(要求:用数组名作为函数的参数来实现)
数据结构·c++·算法
冰红茶兑滴水3 小时前
Linux 线程互斥
linux·c++
liuyang-neu5 小时前
力扣中等 33.搜索旋转排序数组
java·数据结构·算法·leetcode
ganjiee00075 小时前
力扣(leetcode)每日一题 2414 最长的字母序连续子字符串的长度
java·算法·leetcode
咩咩大主教6 小时前
Linux下的简单TCP客户端和服务器
linux·服务器·c语言·开发语言·c++·tcp/ip·网络编程
ly-how6 小时前
leetcode练习 格雷编码
数据结构·算法·leetcode
阿W呀6 小时前
MATLAB-最小二乘辨识
人工智能·算法·matlab
liuyang-neu6 小时前
力扣 中等 162.寻找峰值
数据结构·算法·leetcode