Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create palindrome from existing string by removing characters

How do i determine the length of the longest palindrome you can get from a word by removing zero or more letters.

for eg : amanQQQapl12345anacaZZZnalpaXXXna67890ma
longest palindrome will be of 21 digits.

like image 245
Nitin Kabra Avatar asked May 14 '12 04:05

Nitin Kabra


3 Answers

This can be solved by dynamic programming. Define d[i, j] as the length of longest palindrome in the original string.

If s[i] = s[j], d[i, j] = max(d[i+1, j-1] + 2, d[i, j-1], d[i+1, j]).

Otherwise d[i, j] = max(d[i, j-1], d[i+1, j]).

like image 54
Rambo Avatar answered Sep 19 '22 01:09

Rambo


The longest palindrome in the word W is the longest common subsequence of W and its mirror.

You can compute it in O(n²) time and O(n) space where n is the length of W but if you know that you only need remove few characters to make a palindrome you can have better complexity.

like image 31
Thomash Avatar answered Sep 18 '22 01:09

Thomash


A palidrome can have at most one odd counted letter i.e. the middle letter, and any number of even counted letters.

You can count the frequency of each letter. If it not all or nothing for each letter, add the count/2*2 for each letter and add one if any letter has an odd count.

like image 24
Peter Lawrey Avatar answered Sep 21 '22 01:09

Peter Lawrey