组合字符串以产生最短的输出

时间:2013-10-15 17:44:45

标签: java string substring

我正在为编程作业寻找一些伪代码的帮助。详细信息是here,但对于某些内容:我从文件中收到字符串,然后我需要将所有字符串组合成最短的字符串。例如,ABC AAB CAB可以变成AABCAB,因为字符串中的字母重叠。

 ABC
AAB
   CAB
------
AABCAB

我很难理解我可以用来解决这个问题的逻辑。我想过将字符串按长度-1分割,直到我得到一个字符,然后在其他字符串中查找相同的字符,但它不能很好地工作。

1 个答案:

答案 0 :(得分:1)

效率相当低但是这应该有效:

String findShortestOverlap(String total, ArrayList<String> stringsLeft)
{
    if(stringsLeft.size() == 0) return total;
    String shortest = "";
    boolean first = true;
    for(int i = 0 ; i < stringsLeft.size() ; i++)
    {
         //combine stringsLeft.get(i) with total and call it newTotal. That is find the biggest overlap between these 2 strings.
         newTotal = findShortestOverlap(newTotal, /*copy of stringsLeft with the ith string removed*/);
         if(first || newTotal.length() < shortest.length())
         {
             first=false;
             shortest=newTotal;
         }
    }
    return newTotal
{

我没有测试过这个。我还假设存在更有效的算法,但这是我的蛮力射击。

找出2个字符串之间最大的重叠应该是一个简单的问题,这就是问题的解决方法。

对此方法的第一次调用应为""总计。

在这方面获得一些简单效率的最简单方法是在此函数之外保存一个“全局”变量,保存到目前为止找到的“最短”字符串。如果newTotal比您到目前为止找到的最短字符串短,则只调用newTotal = findShortestOverlap(...)。这可以减少树上的大量空间,如果你在算法的早期找到了一个接近最优的解决方案,它应该很快就可以了。