gpt4 book ai didi

string - 将字符串转换为插入次数最少的回文

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:39:38 24 4
gpt4 key购买 nike

这是https://www.dailycodingproblem.com/的问题:

Given a string, find the palindrome that can be made by inserting the fewest number of characters as possible anywhere in the word. If there is more than one palindrome of minimum length that can be made, return the lexicographically earliest one (the first one alphabetically).

For example, given the string "race", you should return "ecarace", since we can add three letters to it (which is the smallest amount to make a palindrome). There are seven other palindromes that can be made from "race" by adding three letters, but "ecarace" comes first alphabetically.

As another example, given the string "google", you should return "elgoogle".

类似于this所以问题,或this GeeksforGeeks 帖子。相似,但不相同;他们都没有对重复出现提供任何解释,就好像他们凭空抽出解决方案一样,他们也没有重建解决方案,更不用说字典编年史最早的解决方案了。

经过一番思考,我的理解如下:

Observe that for any string s[i..j], if s[i] == s[j], then the number of insertions required to make it a palindrome is the same as the number of insertions required to make s[i+1..j-1] a palindrome.

If, however, s[i] != s[j], then we may convert s[i..j-1] to a palindrome and then insert s[j] at the beginning, or convert s[i+1..j] to a palindrome and insert s[i] at the end. Since we are looking for the fewest number of insertions, we will choose the minimum of the two options. The number of insertions is one more than the number of insertions required for the chosen subproblem (for adding a character at the beginning or at the end).

如何重建字典序最早的解决方案?

最佳答案

首先,让我们回答“我如何重建解决方案”,然后关注排序。假设您将插入的数量存储在二维矩阵 insertions[start][stop] 中,您只需要追溯您的步骤,“收集”插入的字符。我们需要一个新数组来存储输出字符串,其长度等于我们的起始字符串加上最小插入次数。我们还将存储两个索引,指向数组中前后的下一个可用点。

首先比较当前子字符串的第一个和最后一个字母,如果相等,则分别在从前到后的下一个可用位置分配这两个输出字符串。例如,如果我们将 FYRF 作为当前子字符串,我们将分配我们的输出字符串 F..F,其中 . 是未确定的字符.然后我们的子串变成 s[i+1..j-1]YR

如果两个字符不匹配,我们将比较 insertions[i+1][j]insertions[i][j-1],看看哪个更小(至少有一个比 insertions[i][j] 小一个)。如果它们相等,则只选择一个(稍后我们将返回)。将输出字符串中对应于我们复制/插入的子字符串的字母的字符分配到输出字符串的下一个可用前后索引处。也就是说,在 JLL 的情况下,如果我们决定为 JLLJ 添加一个 J,我们将采用子字符串 s[ i+1..j],因此我们将在输出字符串 J..J 中存储 JJ。如果我们的输出字符串已经包含 AR....RA,我们将存储 ARJ..JRA。我们重复整个过程,直到分配完所有字符。

现在,让它按字典顺序排列。关于上一段中 insertions[i+1][j]insertions[i][j-1] 相等的情况,我们不应该选择一个他们是随机的。相反,我们应该按字典顺序比较 s[i]s[i+1],如果 s[i] 先出现,则插入 s[i] 到输出字符串/继续 insertions[i+1][j]。否则,使用 s[i+1]/insertions[i][j-1]。这将为我们提供所有可用选项中字典顺序最快的字符串。

关于string - 将字符串转换为插入次数最少的回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55178669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com