how to convert a string into a palindrome with minimum number of operations?

前端 未结 2 950
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 14:06

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 <

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-05 14:44

    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.

提交回复
热议问题