KMP算法

KMP看了网上很多博文,也看的不是很懂,最后看了这个视频教学,慢慢去理解终于弄懂了~~~挺好的教学。

http://v.youku.com/v_show/id_XNjg0OTk1MTc2.html?from=y1.2-1-87.3.1-2.1-1-1-0


下面是参照视频写的代码,以下为 hihocoder 1015的AC代码:

#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int _next[10005];
void getNext(const string& T)
{
	memset(_next , 0 , sizeof(_next));
	_next[0] = -1 ;
	int len = T.size();
	int i = 0,j = -1 ;  // j 前缀, i 后缀
	while(i < len)
	{
		if(-1 == j || T[i] == T[j])
		{
			i++,j++;
		//	_next[i] = j ;
			if(T[i] != T[j])   //对上一句的优化 
			{
				_next[i] = j ;
			}
			else
			{
				_next[i] = _next[j];
			}
		 
		}
		else
		{
			j = _next[j];
		}
	} 
}
int KMP(const string& s ,const string& T)
{
	int i = 0,j = 0 ;  //i 为原串指针, j 为模式串指针
	int len = s.size();
	int limit = T.size();
	int ans = 0 ;
	while(i < len)
	{
		if(-1 == j || s[i] == T[j])
		{
			i++,j++;
		}
		else
		{
			j = _next[j];
		}
		if(j == limit)
		{
			ans++; 
			j = _next[j];
		}
	} 
	return ans ;
}
int main()
{
	string s , t ;
	int n ;
	cin >> n ;
	while(n--)
	{
		cin >> t >> s ;
		getNext( t );
		cout << KMP(s , t) << endl ;
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值