Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 字串-DP_Algorithm - Fatal编程技术网

Algorithm 字串-DP

Algorithm 字串-DP,algorithm,Algorithm,我有一个字符串,我必须确定最长的子字符串,这样一个单词的最后两个字母必须是它后面的前两个字母 例如,对于单词: 星,神器,书,栉水母,列表,回复 编辑:所以最长的子串应该是星,神器,栉水母,回复 我正在寻找一个解决这个问题的办法。没有代码,我很感激任何关于如何解决它的建议。首先,将所有单词读入一个结构。你真的不需要这样做,但这样做更容易。你也可以边走边读 这个想法是要有一个查找表,比如.NET中的字典,它将包含键值对,这样一个单词的最后两个字母在这个查找表中都有一个条目,并且它们对应的值将始终是

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

例如,对于单词:

星,神器,书,栉水母,列表,回复

编辑:所以最长的子串应该是星,神器,栉水母,回复


我正在寻找一个解决这个问题的办法。没有代码,我很感激任何关于如何解决它的建议。

首先,将所有单词读入一个结构。你真的不需要这样做,但这样做更容易。你也可以边走边读

这个想法是要有一个查找表,比如.NET中的字典,它将包含键值对,这样一个单词的最后两个字母在这个查找表中都有一个条目,并且它们对应的值将始终是迄今为止找到的最长的“子字符串”

时间复杂度开启-您只需浏览列表一次

逻辑:

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语言中的实际工作代码,如果您需要的话:

最接近我的是:

你应该用Id标记每个单词。让我们举个例子:

星形=>可能的第一个子字符串。因为你在寻找最长的子串,如果一个子串与ar成星,它就不是最长的,因为你可以在前面加星。 让我们将星形ID设置为1,其字符串比较为ar

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

book=>在字符串比较中,前两个字符不匹配,只有ct,因此我们将book ID设置为2,并添加一个新的字符串比较:ok

list=>前两个字符与字符串比较中的任何内容都不匹配re from ID==1和ok from ID==2,因此我们创建另一个ID=3和另一个字符串比较

最后,您只需要遍历ID,看看哪个ID的元素最多。你也可以边走边数

这个算法的主要思想是记住我们要寻找的每个子串。如果我们找到了匹配项,我们就用最后两个新字符更新正确的子字符串,如果没有,我们就将其添加到内存列表中


重复此过程使其位于*m上,m是不同ID的数量

你的方法对这两个加粗的词有效吗:星星,神器,阿吉塔,机智,书,栉水母,列表,回复?哦,我没想到这个。。。可能不会。我可以看到如何调整它,但它似乎将复杂性提高到n^2: