数据结构_串_串的模式匹配_KMP算法_C++实现

"head.h"


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

class STRING
{
public:
	void GetString();
	void GetSubString();
	void KMP();
	void Print();
private:
	void GetNext();
	string str;
	string sub;
	int next[1000];
	int strlen;
	int sublen;
};

void STRING::GetString()
{
	cout<<"Please Input The MainString :"<<endl<<endl;
	cin>>str;
	strlen=str.length();
}

void STRING::GetSubString()
{
	cout<<"Please Input The SubString :"<<endl<<endl;
	cin>>sub;
	sublen=sub.length();
}

void STRING::KMP()
{
	cout<<"KMP Method Called !"<<endl<<endl;
	GetNext();
	int i,j;
	i=j=0;
	while(i<strlen&&j<sublen)
	{
		if(j==-1||str[i]==sub[j])
		{
			i++;
			j++;
		}
		else
		{
			j=next[j];
		}
	}
	if(j==sublen)
	{
		cout<<"Succeed ! Position = "<<i-j+1<<endl<<endl;
	}
	else
	{
		cout<<"Failed !"<<endl<<endl;
	}
}

void STRING::Print()
{
	cout<<"Main String = "<<str<<endl<<"    Length = "<<strlen<<endl;
	cout<<"SubString = "<<sub<<endl<<"    Length = "<<sublen<<endl<<endl;
}

void STRING::GetNext()
{
	int i,j;
	next[0]=-1;
	i=0;j=-1;
	while(i<sublen-1)
	{
		if(j==-1||sub[i]==sub[j])
		{
			i++;
			j++;
			if(sub[i]!=sub[j])
				next[i]=j;
			else
				next[i]=next[j];
		}
		else
		{
			j=next[j];

		}
	}
}



"main.cpp"



#include<iostream>
#include"head.h"
using namespace std;

int main()
{
	STRING str;
	char choice;
	while(1)
	{
		cout<<"Your Choice Please ?"<<endl<<endl
			<<"1 . Set Main String"<<endl
			<<"2 . Set SubString"<<endl
			<<"3 . KMP"<<endl
			<<"4 . Print"<<endl
			<<"5 . Quit"<<endl<<endl;
		cin>>choice;
		switch(choice)
		{
		case '1':
			str.GetString();
			break;
		case '2':
			str.GetSubString();
			break;
		case '3':
			str.KMP();
			break;
		case '4':
			str.Print();
			break;
		case '5':
			return 0;
		default:
			cout<<"No Such Choice !"<<endl;
			break;
		}
	}
}


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值