我如何可以计算将一个字符串变成回文所需的字符数?回文、所需、字符串、字符

2023-09-11 22:40:35 作者:潇潇湘水

最近我发现,要你计算字符,需插(任何地方)在一个字符串的最小数目把它变成一个回文比赛的问题。

例如,考虑字符串:abcbd我们可以把它变成一个回文通过插入只有两个人物:后一和另一个D后一句:A ð bcbd < B> A

这似乎是一个要求同样的事情,但字符只能在结尾处增加了类似的问题的概括 - 这在O(N)一pretty的简单的解决方案使用哈希表

我一直在试图修改 Levenshtein距离算法来解决这个问题,但避风港重新成功。如何解决这个问题(这并不一定必须是有效的,我在任何DP解决方案,只是有兴趣),将AP preciated任何帮助。

解决方案 C语言 判断输入的字符是否是 回文 l项读和倒读都一样的字符串称为 回文 ,

请注意:这仅仅是一个好奇心。 DAV提出了可以进行修改,以DP算法运行在O算法(N ^ 2)时间为O(n ^ 2)空间轻松(或许为O(n)具有较好的记账)。

当然,这个天真的算法实际上可能会派上用场,如果你决定改变允许的操作。

下面是一个'naive'ish算法,它大概可以更快地做出巧妙配合记账。

给出一个字符串,我们猜测所产生的回文的中间,然后尝试计算,使串绕,中等回文需要插入的数目。

如果字符串的长度为n,有2n + 1个可能的中段(每个字符,两个字符之间,之前,只是后的字符串)。

假设我们考虑一个中间这给了我们两个字符串L和R(一个向左,一个向右)。

如果我们使用的是插入,我相信最长公共子算法(它是一个DP算法)现在可以所用的创建一个超级的字符串,其中包含L和后退R,请参阅最短常见的超层。

选择中间,让你的最小数字插入。

这是为O(n ^ 3),我相信。 (注:我没有尝试过,证明它是正确的)。

I recently found a contest problem that asks you to compute the minimum number of characters that must be inserted (anywhere) in a string to turn it into a palindrome.

For example, given the string: "abcbd" we can turn it into a palindrome by inserting just two characters: one after "a" and another after "d": "adbcbda".

This seems to be a generalization of a similar problem that asks for the same thing, except characters can only be added at the end - this has a pretty simple solution in O(N) using hash tables.

I have been trying to modify the Levenshtein distance algorithm to solve this problem, but haven't been successful. Any help on how to solve this (it doesn't necessarily have to be efficient, I'm just interested in any DP solution) would be appreciated.

解决方案

Note: This is just a curiosity. Dav proposed an algorithm which can be modified to DP algorithm to run in O(n^2) time and O(n^2) space easily (and perhaps O(n) with better bookkeeping).

Of course, this 'naive' algorithm might actually come in handy if you decide to change the allowed operations.

Here is a 'naive'ish algorithm, which can probably be made faster with clever bookkeeping.

Given a string, we guess the middle of the resulting palindrome and then try to compute the number of inserts required to make the string a palindrome around that middle.

If the string is of length n, there are 2n+1 possible middles (Each character, between two characters, just before and just after the string).

Suppose we consider a middle which gives us two strings L and R (one to left and one to right).

If we are using inserts, I believe the Longest Common Subsequence algorithm (which is a DP algorithm) can now be used the create a 'super' string which contains both L and reverse of R, see Shortest common supersequence.

Pick the middle which gives you the smallest number inserts.

This is O(n^3) I believe. (Note: I haven't tried proving that it is true).