Minimum insertions to form a palindrome

来源:互联网 发布:图书数据哪个网站多 编辑:程序博客网 时间:2024/06/13 22:18

相关问题1:最长回文子串

相关问题2:[LeetCode] Shortest Palindrome I


给你一个字符串S,插入一些字符,把 S 转换成一个回文字符串。

例如:

ab: Number of insertions required is 1. bab
aa: Number of insertions required is 0. aa
abcd: Number of insertions required is 3. dcbabcd
abcda: Number of insertions required is 2. adcbcda which is same as number of insertions in the substring bcd

思路:可以用递归的方法。

The minimum number of insertions in the string str[l…..h] can be given as:
      minInsertions(str[l+1…..h-1])     if str[l] == str[h]
      min(minInsertions(str[l…..h-1]), minInsertions(str[l+1…..h])) + 1  if str[l] != str[h]

0 0