Substrings
题目大意:给定若干字符串,找出其中的最长公共子字符串,输出其长度。要求公共子字符串必须是连续的(中间不能被其他字母隔开),最长公共子字符串在每个字符串中的出现正着反着都行。
思路:先确定输入的字符串中最短的(若有多个最短的其第一个即可),再用SUBSTR以这个最短的字符串为准,由长至短在所有字符串中进行搜索,取搜索到的第一个公共子串(即为最长公共子串)。
代码:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int n,k,length,num,p;
string str[100],temp;
cin>>n;
while(n--)
{
p=0;
length=101;
cin>>num;
for(int i=0;i<num;i++) //输入字符串并取出最短的
{
cin>>str[i];
if(str[i].length()<length)
{
length=str[i].length();
k=i;
}
}
int f=0,b=str[k].length(); //f为取字符的开始位置,b为所取字符的个数
for(temp=str[k];temp.length()>0;)
{
int j;
char *temp2=new char[temp.length()+1];
int c,d;
for(c=temp.length()-1,d=0;c>=0;c--,d++) //取子字符串的反串
temp2[d]=temp[c];
temp2[d]='\0';
for(j=0;j<num;j++) //搜索
{
int t;
for(t=0;str[j].length()-t>=temp.length();t++)
if(str[j].substr(t,temp.length())==temp||str[j].substr(t,temp.length())==temp2)break;
if(str[j].length()-t<temp.length())break;
}
if(j==num){cout<<temp.length()<<endl;break;}
if(f<p) //子字符串移位与改变长度
f++;
else
{
f=0;
b=str[k].length()-++p;
}
temp=str[k].substr(f,b);
}
if(temp.length()==0)cout<<0<<endl;
}
return 0;
}