如何将单词分成不同的方式,使其成为另外两个单词的串联

时间:2012-06-15 17:25:34

标签: algorithm

我刚刚在网上遇到了这个有趣的问题,我对如何在这方面取得进展感到非常难过。

Write a function that finds all the different ways you can split up a word into a
concatenation of two other words.

这是后缀树用于什么的东西吗?

我不是在寻找代码,只是寻找前进的概念方法。

3 个答案:

答案 0 :(得分:6)

一些伪代码:

   foreach place you can split the word:
    split the word.
    check if both sides are valid words.

答案 1 :(得分:2)

如果您正在寻找一个好的答案,请告诉我们您对有效单词的定义。

假设一个单词是在字母表上定义的字符串,其长度大于零。您可以使用后缀树。

下面是一个简化的算法,只花费O(n)时间。

Convert the word into a character array.

Traverse through the length of the array and for each i just take two strings (0 to i) and 
(i+1     to    length of the array-1).  

请记住覆盖长度大于零的基本条件。

答案 2 :(得分:-2)

只有在满足以下条件的情况下,使用此方法的总数可以大于一个:

->两个单词之一必须是另一个单词的倍数。例如:“ abcd”和“ abcdabcd”。 使用这两个词,您可以通过许多不同的方式形成字符串“ abcdabcdabcdabcd”。

因此,首先检查这种情况。

然后检查是否可以以任何方式从两个单词写入字符串。然后简单的数学应该给你答案