问题:Catcher是MCA国的情报员,他工作时发现敌国会用一些对称的密码进行通信,比如像这些ABBA,ABA,A,123321,但是他们有事会在开始或结束时加入一些无法的字符以防止别国破解。比如进行如下列变化,ABBA->12ABBA,ABA->ABAKK,123321->51233214。因为截获的串太长了,而且存在多种可能的情况(abaaab可看走是aba,或者baaab的加密形式),Cather的工作量实在是太大了,他只能像电脑高手求助,你能帮Cather找出最长的有效密码串吗?
方法一:将原字符串与其逆序字符串进行比较
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int MaxSubstr(const string &a,const string &b,string &c)
{
int start1,start2;
int count=0,Max=0;
for(int i=0;i<a.size();i++)
for(int j=0;j<b.size();j++)
{
start1=i,start2=j;
while(a[start1]==b[start2] && start1<a.size() && start2<b.size())
{
count++;
start1++;
start2++;
}
if(count>Max)
{
Max=count;
//begin=i;
c.clear();
c=a.substr(i,Max);//注意从i开始
}
count=0;
}
return Max;
}
int main()
{
string s1,s2;
cin>>s1;
s2=s1;
string s3;
//char* s3=new char[s1.size()+1];
reverse(s2.begin(),s2.end());
cout<<s2<<endl;
//int start;
int maxLength=MaxSubstr(s1,s2,s3);
cout<<s3<<":";
cout<<maxLength<<endl;
return 0;
}
方法二:后缀数组求最长回文子串
思想:将字符串与其逆序用特殊符号连接,构造后缀数组,求后缀数组中的最长公共前缀
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int pstrcmp(const void *a,const void *b)
{
return strcmp(*(char **)a,*(char **)b);
}
int comlen_suff(char *p,char *q)
{
int len=0;
int count=0;
while(*p && *q && *p++ == *q++)
{
len++;
if(*p =='#' ||*q =='#')
break;
}
while(*p)
{
if(*p++=='#')
{
count++;
break;
}
}
while(*q)
{
if(*q++ == '#')
{
count++;
break;
}
}
if(count==1)
return len;
else
return 0;
}
int LPS(char *s)
{
char *suff[1000];
int maxlen=0,maxIndex;
int len=strlen(s);
int len_suff=2*len+1;
char *arr=new char[len_suff+1];
strcpy(arr,s);
arr[len]='#';
char *p=s;
char *q=arr+len_suff;
*q='\0';
while(*p)
*--q=*p++;
for(int i=0;i<len_suff;i++)
suff[i]=&arr[i];
qsort(suff,len_suff,sizeof(char*),pstrcmp);
for(int i=0;i<len_suff-1;i++)
{
int com_len=comlen_suff(suff[i],suff[i+1]);
if(com_len>maxlen)
{
maxlen=com_len;
maxIndex=i;
}
}
printf("%.*s\n",maxlen,suff[maxIndex]);
delete []arr;
return maxlen;
}
int main()
{
printf("%d\n",LPS("aabaab"));
return 0;
}