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

前端 未结 2 951
爱一瞬间的悲伤
爱一瞬间的悲伤 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:32

    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.

提交回复
热议问题