HDU1711 KMP水题

废话不多说
是一道练习oj的I/O和KMP的优秀水题
因为数据量大而且重复字符多,所以蛮适合KMP

虽然没用strstr试过就是啦(各个语言实现都差不多,没用什么C++的特性和
题目:
在这里插入图片描述源码:

#include <iostream>//cout<< cin>>
#include <stdio.h> 
#include <cstring>
using namespace std;

int len_target;
int len_pattern;
void get_next(int pattern[],int next[])
{//获得next数组
	int i = 0;// 遍历pattern的index
	int j = -1;//回溯用的index
	next[0] = -1;
	while(i<len_pattern-1)
	{
		if(j ==-1 || pattern[j]==pattern[i])//初始化字符换或者模式匹配成功
		{
			i++;
			j++;
			next[i] = j;//从第一个(0)开始
		}
		else
		{
			j = next[j];//回溯
		}
	}
}

int kmp_search(int target[], int pattern[], int next[])
{//实现最为基本的KMP算法
	int tar_index = 0;
	int par_index = 0;
    while(par_index<len_pattern && tar_index<len_target)
	{
		if(par_index == -1 || pattern[par_index]==target[tar_index])
		{
			tar_index++;
			par_index++;
		}
		else
		{
			par_index = next[par_index];
		}
	}
	if(par_index==len_pattern)
	{
		return tar_index-par_index+1;
	}
	return -1;
}


int main()
{
	int count;
	cin>>count;
	int next[10000];
	int target[1000000];
	int pattern[10000];
	for(;count>0;count--)
	{
		cin>>len_target>>len_pattern;
		for(int i=0; i<len_target; i++)
		{
			cin>>target[i];
		}
		for(int j=0; j<len_pattern; j++)
		{
			cin>>pattern[j];
		}
		get_next(pattern, next);
		cout<<kmp_search(target,pattern, next)<<endl;
	}
return 0;
}

下面是本地结果
在这里插入图片描述

然后AC

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值