7-2 jmu-ds-最长公共子串 (10分)
给出2个字符串,输出2字符串的最长公共子串。
输入格式:
输入2个字符串,不可包含空格。
输出格式:
输出2个字符串的最长公共子串。若没有公共子串,则输出“NULL”
输入样例1:
abcding
sbcdiofng
输出样例1:
bcdi
输入样例2:
understanding
fw
输出样例2:
NULL
#include <iostream>
#include <string>
typedef struct MyString* StrPoint;
struct MyString{
char data;
StrPoint Link;
};
class Array1{
private:
StrPoint Front,Rear;
int Length,MaxInit,MaxLength;
public:
Array1(){
this->Length=0;
this->Front=(StrPoint)malloc(sizeof(struct MyString));
this->Rear=Front;
this->Front->Link=NULL;
this->Length=0;
}
void FindMaxSequence(){
if(this->Front->Link==NULL){
std::cout<<"NULL\n";
return;
}
StrPoint InitP=this->Front;
this->MaxInit=0;
this->MaxLength=0;
int TempInitNum=0;
int i=0;
for(i=this->MaxInit;i<this->Length;i++){
if(InitP->data>=48&&InitP->data<=57){
TempInitNum++;
if(TempInitNum>this->MaxLength){
this->MaxLength=TempInitNum;
this->MaxInit=i-TempInitNum;
}
} else{
TempInitNum=0;
}
InitP=InitP->Link;
}
std::cout<<this->MaxInit+1<<" "<<this->MaxLength<<"\n";
}
StrPoint InputString(){
char ch1;
ch1=getchar();
while(ch1!='\n'){
this->Rear->data=ch1;
StrPoint NewStrP=(StrPoint)malloc(sizeof(struct MyString));
NewStrP->Link=NULL;
this->Rear->Link=NewStrP;
this->Rear=NewStrP;
ch1=getchar();
this->Length++;
}
return this->Front;
}
void StrOutPutString(StrPoint P){
while (P->Link!=NULL){
std::cout<<P->data<<" \n";
P=P->Link;
}
}
int GetLength(){
return this->Length;
}
StrPoint GetFrontPoint(){
return this->Front;
}
};
class SequenceSaver{
public:
StrPoint P1;
StrPoint P2;
int StrNum;
SequenceSaver(){
P1=(StrPoint)malloc(sizeof(struct MyString));
P2=(StrPoint)malloc(sizeof(struct MyString));
P1->Link=NULL;
P2->Link=NULL;
StrNum=0;
}
void PrintNode(){
if(this->StrNum==0){
std::cout<<"NULL\n";
return;
}
for(;P1!=P2;P1=P1->Link){
std::cout<<P1->data;
}
}
};
void FindMaxSequence(Array1* arr1,Array1* arr2){
Array1* TempPmin=(arr1->GetLength()<arr2->GetLength())?arr1:arr2;
Array1* TempPmax=(arr1->GetLength()>arr2->GetLength())?arr1:arr2;
StrPoint StrMin=TempPmin->GetFrontPoint();
StrPoint StrMax=TempPmax->GetFrontPoint();
SequenceSaver* SePointer=new SequenceSaver();
SePointer->StrNum=0;
for(;StrMin->Link!=NULL;StrMin=StrMin->Link){
for(StrPoint StrMax2=StrMax;StrMax2->Link!=NULL;StrMax2=StrMax2->Link){
StrPoint StrMinCopy=StrMin;
StrPoint StrMaxCopy=StrMax2;
int StrNum=0;
while (StrMaxCopy->data==StrMinCopy->data){
StrNum++;
StrMaxCopy=StrMaxCopy->Link;
StrMinCopy=StrMinCopy->Link;
if((StrMaxCopy==NULL&&StrMinCopy==NULL)||(StrMaxCopy->data!=StrMinCopy->data)){
if(StrNum>SePointer->StrNum){
SePointer->StrNum=StrNum;
SePointer->P1=StrMin;
SePointer->P2=StrMinCopy;
}
break;
}
}
}
}
SePointer->PrintNode();
}
int main() {
Array1* arr1=new Array1();
Array1* arr2=new Array1();
arr2->InputString();
arr1->InputString();
FindMaxSequence(arr1,arr2);
}