大话数据结构——KMP算法(还存在问题)

http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html

/*#include<iostream>
#include <string>
using namespace std;

int count_same_char(string T,int j);

void get_next(string T,int *next)
{
	int j=1;
	next[1]=0;
	for(int k=2;k<=T.size();++k)
	{
		next[k]=count_same_char(T,k)+1;		
	}
}

//返回字符串T中0到j-1个字符串,有多少个前后缀是相等的
//若没有返回0
int count_same_char(string T,int j)
{
	j=j-1;
	int cout_number=0;
	int director=0;
	for(int i=(j/2);i>=1;i--)//假设前后缀相等的字符个数
	{
		for(int k=0;k<i;k++)
		{
			if(T[k]!=T[j-i+k])
			{director=0;break;}
			director=1;
		}
		if(director==1)
		{cout_number=i;break;}
	}
	return cout_number;
}
int main()
{

	string T="ababaaaba";
	int next[10];
	get_next(T,next);
	for(int i=1;i<=T.size();++i)
	{
		cout<<next[i]<<' ';
	}
	cout<<endl;

	/*string T="abcabx";
	cout<<count_same_char(T,6)<<endl;
	*/
/*
	system("pause");
	return 1;
}*/

#include<iostream>
#include <string>
using namespace std;

int get_number(string T,int j);

void get_char_number(string T,int *next)
{
  next[0]=0;
  int K=T.size();
  for(int i=1;i<K;i++)
  {
	  next[i]=get_number(T,i);
  }
}

int get_number(string T,int j)
{
	int count_number=0;
	int i,k,temp;
	for(k=(j+1)/2;k>=1;k--)
	{
		temp=0;
		for(i=0;i<k;i++)
		{
			if(T[i]!=T[j-k+i+1])
			{temp=1;break;}
		}
		if(temp==0)
		{count_number=k;break;}
	}
	return count_number;
}

int KMP(string S,string T)
{
	int next[100];
	int result[100];
	get_char_number(T,next);

	if(T.size()>S.size())
		return -1;
	int i=0;//在S中的起始搜索位置
	while(i<=(S.size()-T.size()))
	{
		int j,temp=1;
		for(j=0;j<T.size();j++)
		{
			if(T[j]!=S[i+j])
			{temp=0;break;}
		}
		if(temp=1)
			return i;
		if(j==0)
			i++;
		i=i+j-next[j-1];
	}
	return -1;
}
int main()
{	
/*
	string T="jkl";
    //cout<<get_number(T,4)<<endl;
	int next[10];
	get_char_number(T,next);
	for(int i=0;i<T.size();i++)
		cout<<next[i]<<' ';
	cout<<endl;
	*/

	string S="fghjkl";
	string T="jkl";

    cout<<KMP(S,T)<<endl;


	system("pause");
	return 1;

}

  

转载于:https://www.cnblogs.com/yanliang12138/p/4347838.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值