五、详细设计
#include<string>
#include<fstream>
#include<cstdlib>
#include<time.h>
using namespace std;
#define MAX 100000
#define M 69
class String
{
private:
int n;
char *str;
int *count; //记录子串在主串中出现的位置
int Find(int i,String &P); // 简单匹配算法找到最近的匹配串后立即停止,而不向下继续且缺乏一个数组记录位置
int *f ; //记录失败函数
void Fail();
int KMPFind(int i,String &P); //改进的失败函数
void ImproveFail();
int KMPFindImprove(int i,String &P);
public:
String(); //建立一个空串
String(const char *p);
String(const String &p); //拷贝函数
~String();
int Length() {return n;}; //返回当前串对象长度
void Output() {cout<<str;}; //输出字符串
int Find(String &P); //简单匹配算法
int KMPFind(String &P); //KMP匹配算法
int KMPFindImprove(String &P); //改进的KMP匹配算法
void Output2(); //输出子串在主串中出现的位置
};
int String::KMPFindImprove(String &P)
{
int sum=0;
int j=KMPFindImprove(0,P);
while(j!=-1)
{
count[sum++]=j;
if(j<=n-P.n) j=KMPFindImprove(j+P.n,P);
}
return sum;
}
void String::Output2() //输出子串在主串中的位置
{
int i=0;
while(count[i]!=count[i+1] && i<MAX-1) //若不再有新的子串匹配,则count[i]与count[i+1]均为0
{
cout<<count[i]<<" ";
i++;
}
}
void menu()
{
cout<<"********************************************"<<endl;
cout<<endl;
cout<<endl;
cout<<" 1.简单模式匹配算法"<<endl;
cout<<endl;
cout<<endl;
cout<<" 2.KMP模式匹配算法"<<endl;
cout<<endl;
cout<<" 4.退出"<<endl;
cout<<endl;
cout<<endl;
cout<<"################################################"<<endl;
}
void main()
{
int choice=0;
menu();
clock_t start,finish;
while(choice!=4)//循环可以连续选择
{
cout<<"请输入选择"<<endl;
cin>>choice;
if(choice==1)
{
String s1("Through aretro spectivelook at the mathe matics teaching at USTC, this article summarizes university's teaching achievements in past 45 years.");
s1.Output();
cout<<endl;
String s2("teaching");
start=clock();
int m=s1.Find(s2);
s2.Output();
cout<<"出现的次数为:"<<m<<endl;
if(m!=0)
{
cout<<"匹配的位置是";
s1.Output2();
cout<<endl;
}
finish=clock();
cout<<endl<<"time is:"<<(double)(finish-start)/CLK_TCK<<endl;
}
if(choice==2)
{
clock_t start,finish;
start=clock();
String s1("Through a retrospective look at the mathematics teaching at USTC, this article summarizes university's teaching achievements in past 45 years.");
s1.Output(); cout<<endl;
String s2("teaching");
s2.Output(); cout<<endl;
int n=s1.KMPFind(s2);
cout<<"出现的次数为:"<<n<<endl;
if(n!=0)
{
cout<<n<<"匹配的位置是";
s1.Output2();
cout<<endl;
}
finish=clock();
cout<<endl<<"time is:"<<(double)(finish-start)/CLK_TCK<<endl;
}
if(choice==3)
{
clock_t start,finish;
start=clock();
String s1("Through a retrospective look at the mathematics teaching at USTC, this article summarizes university's teaching achievements in past 45 years.");
s1.Output(); cout<<endl;
String s2("teaching");
s2.Output(); cout<<endl;
int n=s1.KMPFindImprove(s2);
cout<<"出现在主串中的次数为:"<<n<<endl;
if(n!=0)
{
cout<<n<<"匹配的位置是";
s1.Output2();
cout<<endl;
}
finish=clock();
cout<<endl<<"time is:"<<(double)(finish-start)/CLK_TCK<<endl;
}
}
}。