KMP

本文详细介绍KMP算法原理及其实现过程,并提供了一个使用C++编写的查找子串在母串中位置的具体实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<pre name="code" class="cpp"><span style="background-color: rgb(0, 153, 0);"><span style="font-size:14px;">题目要求:</span></span>
    用KMP算法实现查找子串在母串中的位置。
<span style="background-color: rgb(0, 153, 0);"><span style="font-size:14px;">代码实现:</span></span>
<pre name="code" class="cpp">
#include "stdafx.h"
#include <stdio.h>
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>  
using namespace std;  
/*
void print(int n)  
{  
cout<<n<<'\0';  
} 
*/
int find_substring(string pattern, string text)
{
	int n = (pattern.size()-1);
	vector<int>next(n+1, 0);
	int i=1,j=0;
	while(i<n)
	{
		if (j==0||pattern[i]==pattern[j])
		{
			++i;
			++j;
			if(pattern[i]!=pattern[j]) 
				next[i]=j;
			else
				next[i]=next[j];
			cout<<"asdfa:"<<i<<":"<<next[i]<<endl;
		}
		else
			j=next[j];
	}
	//vector<int>::iterator itor;
	//for_each(next.begin(),next.end(),print);//用for_each进行遍历    
	//cout<<endl;  
	i=0;
	j=1;
	while(i<text.size()&&j<pattern.size())
	{
		if(j==0||text[i]==pattern[j])
		{
			++i;
			++j;
		}
		else j=next[j];
	}
	if(j>n)
		return i-n;
	else return 0;
}

void main ()
{
	/*char* who = "I"; `
	char* whom = "优快云";
	char s[32];
	//char * s;字符串常量不能更改,所以存成数组
	sprintf(s, "%s love %s.", who, whom);
	cout<<s<<endl;
	cout<<sizeof(s)<<endl;//32
	cout<<strlen(s)<<endl;//12
	char * str="abaabcac";
	int n=strlen(str);
	cout<<n<<endl;
	char *strtemp=new char[n];
	//当用char str[n];时不行
	sprintf(strtemp,"%d%s",n,str);
	string pattern=string(strtemp);
	cout<<"pattern:"<<pattern<<endl;
	*/
	int *next=new int[9];
	string pattern="1abaabcac";//数据结构书上第一个为串长,这里为1
	string text="1acaccbabbabaabcac";
	int out=find_substring(pattern,text);
	cout<<out<<endl;
	getchar();
}





                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值