字串的连接最长路径查找

描述

给定n个字串,其中一个字串的后m个字符,是下一个字串的开始。

找出所有字串中的能连接起来的最长路径。

知识点查找,排序
运行时间限制10M
内存限制128
输入

 

输出

 

样例输入ABCC ABCD BCCE BCDE CCEF BCCE CCEG CEGF
样例输出ABCCEGF
#include<iostream>
#include<vector>
#include<string>
using namespace std;
#define NUM 100
vector<string>K;
int con[NUM][NUM];
bool iscon(int index1,int index2)
{
string stemp1,stemp2;
for (int i=K[index1].length();i>0;i--)
{
stemp1=K[index1].substr(K[index1].length()-i,K[index1].length());
stemp2=K[index2].substr(0,i);
if(stemp1==stemp2)return true;
}
return false;
}
string getpath(string src, int index)
{
string stemp1, stemp2;
for (int i = K[index].length(); i > 0; i--)
{
stemp1 = K[index].substr(0, i);
stemp2 = src.substr(src.length() - i, i);
if (stemp1 == stemp2)
{
return src+ K[index].substr(i, K[index].length() - i);
}
}
return NULL;
}
string find(int index,string src)
{
int L = 0,t=0,P=0;
string *ss = new string[K.size()];
if (index == K.size()-1)return src;
for (int j = index+1; j < K.size(); j++)
{
if (con[index][j])ss[t++]=find(j, getpath(src,j));
}
for (int j = 0; j < t; j++)
{
if (ss[j].length()>L){L = ss[j].length();P=j;}
}
return ss[P];
}
int main()
{
int index,N;
string st;
vector<string>result;
getline(cin,st); 
while ((index=st.find(' '))!=string::npos)
{
string temp(st,0,index);
K.push_back(temp);
st=st.substr(index+1);
}
K.push_back(st);
N=K.size();
for (int i=0;i<N-1;i++)
{
for (int j=i+1;j<N;j++)
{
if(iscon(i,j))
con[i][j]=1;
else con[i][j]=0;
}
}
for (int i = 0; i < N-1; i++)
{
result.push_back(find(i, K[i]));
}
int L = 0,p=0;
for (int j = 0; j < result.size(); j++)
{


if (result[j].length()>L){L = result[j].length();p=j;}
}
cout << result[p] << endl;
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值