如何以最少的操作次数将字符串转换为回文?

发布于 2024-10-12 19:20:38 字数 393 浏览 11 评论 0原文

这是 问题 表示以最少的操作次数将字符串转换为回文。我知道它类似于 Levenshtein 距离 但我还无法解决它

例如,对于输入mohammadsajjadhossain,输出是8

Here is the problem states to convert a string into a palindrome with minimum number of operations. I know it is similar to the Levenshtein distance
but I can't solve it yet

For example, for input mohammadsajjadhossain, the output is 8.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

裂开嘴轻声笑有多痛 2024-10-19 19:20:38

对字符串及其反面执行 Levenshtein 距离。解决方案将是 DP 数组的对角线中从左下角到右上角的操作的最小值,以及对角线上方和下方的每个条目。

这是有效的,因为沿对角线的条目表示使字符串的前 i 和最后 Ni 字符相等所需的最小编辑量,而上方和下方的条目表示以奇数长度结尾的字符串的最小值,其中中间(左) -over) 字符与任何内容都不匹配。

Perform Levenshtein distance on the string and its reverse. The solution will be the minimum of the operations in the diagonal of the DP array going from bottom-left to top-right, as well as each entry just above and just below the diagonal.

This works because the entries along the diagonal represent the minimum edits required to make the first i and last N-i characters of the string equal and the entries just above and just below represent the minimum for strings ending up with odd-length where the middle (left-over) character doesn't match against anything.

薄荷→糖丶微凉 2024-10-19 19:20:38

您只需要计算有限数量的编辑距离,每个可能的回文枢轴点一个。枢轴点可以是一个字母,也可以位于两个字母之间,因此长度为 n 的字符串有 2n-1 个枢轴点。对于每个枢轴点,您计算枢轴点之前的字符及其之后的字符的反向编辑距离:

(m)ohammadsajjadhossain: Levensthein("", "niassohdajjasdammaho")
m ohammadsajjadhossain:Levensthein("m", "niassohdajjasdammaho")
m(o)hammadsajjadhossain: Levensthein("m", "niassohdajjasdammah")
mo hammadsajjadhossain:Levensthein("mo", "niassohdajjasdammah")
mo(h)ammadsajjadhossain: Levensthein("mo", "niassohdajjasdamma")
moh ammadsajjadhossain:Levensthein("moh", "niassohdajjasdamma")
等等。

现在只需取这些距离中的最小值即可。如果速度很重要,您可以优化掉许多此类调用。

You just need to compute a limited number of Levenshtein distances, one for each possible palindrome pivot point. A pivot point can be a letter or it can be between two letters, so a string of length n has 2n-1 pivot points. For each pivot point, you calculate the Levenshtein distance of the characters before the pivot point and the reverse of the characters after it:

(m)ohammadsajjadhossain: Levensthein("", "niassohdajjasdammaho")
m ohammadsajjadhossain: Levensthein("m", "niassohdajjasdammaho")
m(o)hammadsajjadhossain: Levensthein("m", "niassohdajjasdammah")
mo hammadsajjadhossain: Levensthein("mo", "niassohdajjasdammah")
mo(h)ammadsajjadhossain: Levensthein("mo", "niassohdajjasdamma")
moh ammadsajjadhossain: Levensthein("moh", "niassohdajjasdamma")
etc.

Now just take the minimum of these distances. If speed is important, you can optimise away many of these calls.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文