字串 - DP

时间:2014-12-08 15:56:25

标签: algorithm

我有一串单词,我必须确定最长的子字符串,这样一个单词的最后2个字母必须是后面一个单词的前2个字母。

例如,对于单词:

st ar ar tifa ct ,预订, ct enopho 重新 ,列表,重新 ply

编辑:所以最长的子字符串是st ar ar tifa ct ct enopho 重新重新 ply

我在 O(n)中寻找解决此问题的想法。没有代码,我很欣赏任何解决方法。

2 个答案:

答案 0 :(得分:0)

首先,将所有单词读入结构中。 (你不是真的需要,但这样工作更容易。你也可以随时阅读它们。)

想法是拥有一个查找表(例如.NET中的Dictionary),它将包含键值对,这样一个单词的每两个最后一个字母在此查找表中都有一个条目,并且它们的相应的值将始终是最长的子字符串'发现到目前为止。

时间复杂度为O(n) - 您只需浏览一次列表。

逻辑:

maxWord <- ""
word <- read next word
initial <- get first two letters of word
end <- get last two letters of word

if lookup contains key initial //that is the longest string so far... add to it
    newWord <- lookup [initial] value + ", " + word
    if lookup doesn't contain key end //nothing ends with these two letters so far
        lookup add (end, newWord) pair
    else if lookup [end] value length < newWord length //if this will be the longest string ending in these two letters, we replace the previous one
        lookup [end] <- newWord
    if maxWord length < newWord length //put this code here so you don't have to run through the lookup table again and find it when you finish
        maxWord <- newWord
else //lookup doesn't contain initial, we use only the word, and similar to above, check if it's the longest that ends with these two letters
    if lookup doesn't contain key end
        lookup add (end, word) pair
    else if lookup [end] value length < word length
        lookup [end] <- word
    if maxWord length < word length
        maxWord <- word

maxWord变量将包含最长的字符串。

如果您需要,这是C#中的实际工作代码:http://pastebin.com/7wzdW9Es

答案 1 :(得分:0)

我最接近 O(n)的是:

你应该标记每个带有Id的单词。我们举个例子:

st ar =&gt;第一个子串可能。由于您正在寻找最长的子串,如果子串以 ar 星形,则它不是最长的,因为您可以在前面添加星。 我们将星标识设为 1 ,其字符串比较为 ar

ar tifa ct =&gt;两个第一个字符匹配第一个可能的子字符串。我们也将工件ID设置为 1 ,并将字符串比较更改为 ct

预订 =&gt;两个第一个字符与字符串比较中的任何内容都不匹配(那里只有 ct ),所以我们将图书ID设置为 2 ,我们添加一个新的字符串比较:确定

...

列表 =&gt;前两个字符与字符串比较中的任何内容都不匹配(重新来自ID == 1和确定来自ID == 2),因此我们创建了另一个ID = 3和另一个字符串比较

最后,您只需要查看ID并查看哪个ID最多。你可以随便计算它。

这个算法的主要思想是记住我们正在寻找的每个子字符串。如果我们找到一个匹配项,我们只用两个新的最后一个字符更新正确的子字符串,如果我们不这样做,我们将它添加到“内存列表”

重复此过程使其 O(n * m) m 不同ID的数量。