KMP字符串算法

#include <iostream>
#include <string>
#include <vector>
using namespace std;
//求next数组
vector<int> Next_arr(const string& s) {
	vector<int>v(s.size());
	v[0] = -1;  //默认v[0] = -1  v[1] = 0
	v[1] = 0;
	int cur_jump = 0, i = 2;  //
	while (i < s.size()) {
		if (s[i - 1] == s[cur_jump]) {
			v[i++] = ++cur_jump;
		}
		else if (cur_jump > 0) {
			cur_jump = v[cur_jump];
		}
		else {
			v[i++] = 0;
		}
	}
	return v;
}
int main()
{
	//vector<int>s(9999);
	//cout << s.size();
	//在str_a里找str_b
	string str_a, str_b;
	
	cin >> str_a;
	cin >> str_b;
	int a_i, b_j;
	vector<int>next = Next_arr(str_b);
	//int next[str_b.size()];
	a_i = b_j = 0;
	cout << next.size();
	while (b_j<str_b.size()&& a_i < str_a.size()) {
		if (str_a.at(a_i) == str_b.at(b_j)) {
			a_i++;
			b_j++;
		}
		else if (b_j>0) {
			b_j = next[b_j];
		}
		else {
			a_i++;
		}
	}
	cout << "-------------------";
	*****//stl提供的kmp算法  直接调用即可 *****
	cout << str_a.find(str_b) << endl;
	cout<<( b_j == str_b.size() ? a_i - b_j : -1);
	return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值