How can I compute the number of characters required to turn a string into a palindrome?

前端 未结 3 1249
予麋鹿
予麋鹿 2020-12-15 20:50

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.

3条回答
  •  失恋的感觉
    2020-12-15 21:26

    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).

提交回复
热议问题