C++ KMP代码的具体实现。

KMP算法C++代码的实现。

#include <iostream>
#include <string>
#include <windows.h>
#include <vector>
using namespace std;


//朴素法找字串
int Index(string S, string T)
{
	
	int i = 0, j = 0;
	while (i <S.length() && j < T.length())
	{
		if (S[i] == T[i])
		{
			i++; j++;
		}
		else
		{
			i = i - j + 2;
			j = 1;
		}
	}
	if (j > T.length())
		return i - T.length();
	else
		return 0;
}


//求模式串T的next数组
void get_next(string T, vector<int>& next)
{
	if (T.length() == 1)
	{
		next.push_back(-1);
	}
	next.resize(T.length());
	next[0] = -1;
	next[1] = 0;
	int i = 2; //i 为要求子字符串字符next数组的下标
	int cn = 0;//cn等于跳转
	while (i < next.size())
	{
		if (T[i - 1] == T[cn])//这个字符的前一个字符 和 跳转的字符(cn-1)的后一个字符即为cn.
		{
			/*cn++;
			next[i] =cn;
			i++*/
			next[i++] = ++cn;
		}
		else if (cn > 0)//我还可以往前跳
		{
			cn = next[cn];
		}
		else//已经在0位置 跳不过去了
		{
			next[i] = 0;
			i++;
		}
	}
}
//KMP算法  S是主串,T是子串
int Index_KMP(string S, string T)
{
	if (S == "" || T == "" || S.length() < 1 || S.length() < T.length())
	{
		return -1;
	}
	int i = 0, j = 0;
	vector<int> next;
	get_next(T, next);
	while (i < S.length() && j < T.length())
	{
		if (S[i] == T[j])
		{
			++i; 
			++j;
		}
		else if (next[j] == -1)
		{
			i++;
		}
		else
		{
			j = next[j];
		}
	}
	return j == T.length() ? i - j : -1;
}



int main()
{
	string a = "abcdefg";
	string b = "cde";
	cout << Index_KMP(a, b);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值