字符串连接

有n 个长为m+1 的字符串,
如果某个字符串的最后m 个字符与某个字符串的前m 个字符匹配,则两个字符串可以联接,
问这n 个字符串最多可以连成一个多长的字符串,如果出现循环,则返回错误

 

//-------------------------------------

这道题可以使用图的方法来求解,能相连的点看成是中间有一条连线,最后简化为先构建一个图,然后从图中查找最长路径,如果出现环,报错。

#include "loop.h"
#include <vector>
#include <string>
#include <iostream>
#include <deque>
using namespace std;

int LongestPath(int* graph, int n, int * indeep )
{
 int max = 0;
 bool* visit = (bool*) malloc(sizeof(bool) * n);
 memset(visit, 0, sizeof(bool) * n);

 deque<int> point;
 for (int i = 0; i < n; i++)
 {
  //find the first indeep is zero behind i
  while(i < n && indeep[i]) i++;
  if (i == n)
   break;
  //use width first to find the longest path
  int pathlong = 0;
  point.clear();
  point.push_back(i);
  point.push_back(-1);
  memset(visit, 0, sizeof(bool) * n);
  visit[i] = true;
  while(!point.empty())
  {
   int index = point.front();
   point.pop_front();
   if(index < 0)
   {
    if (!point.empty())
    {
     point.push_back(-1);
     pathlong++;
    }
   }
   else
   {
    for(int j = 0; j < n; j++)
    {
     if (graph[ index*n + j] )
     {
       if(!visit[j]){
        point.push_back(j);
        visit[j] = true;
       }else{
        cout<<"there is a loop"<<endl;
        return -1;
       }
     }
    }
   }
  }
  if(pathlong > max)
   max = pathlong;
 }
 free(visit);
 return max;
}
/*
有n 个长为m+1 的字符串,
如果某个字符串的最后m 个字符与某个字符串的前m 个字符匹配,则两个字符串可以联接,
问这n 个字符串最多可以连成一个多长的字符串,如果出现循环,则返回错误。
*/
int LongestConection(vector<string> bag, int m)
{
 int n = bag.size();
 //initial graph
 int* graph = (int*) malloc(sizeof(int) * n * n);
 memset( graph, 0, sizeof(int) * n * n);
 
 int* indeep = (int*) malloc(sizeof(int) * n);
 memset(indeep, 0, sizeof(int)*n);

 for(int i = 0; i < n; i++)
  for(int j = 0; j <n; j++)
  {
   if (j != i && strncmp(bag[i].c_str()+1, bag[j].c_str(), m) == 0)
   {
    graph[i*n+j] = 1;
    indeep[j]++;
   }
  }

 int result = LongestPath(graph, n, indeep);
 free(graph);
 free(indeep);
 if (result < 0)
  return -1;
 return result + m+1;
}


int main()
{
 vector<string> bag;
 bag.push_back("abc");
 bag.push_back("bcd");
 bag.push_back("cda");

 int m = 2;

 int result = LongestConection(bag, m);
 if ( result < 0){
  cout<<"there is a loop "<<endl;
  return 0;
 }
 cout<<"the longest connect is : "<<result<<endl;
 getchar();
 return 0;

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值