Create palindrome from existing string by removing characters

送分小仙女□ 提交于 2019-11-29 05:01:22
Rambo

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

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.

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.

This is proper implementation of the answer by @Rambo, in case other finds his answer too laconic. I have added caching of previous results but under the condition that the maximum number of distinct symbols is at most 1000. This provides significant speedup due to multiple branches using same sub-branches.

int d[1000][1000] = {0}; // To store result of previous computation

int computeMaxPalindromeLength(vector<int>& a, int start, int end) {
    if(d[start][end] != 0) // If not precomputed, recompute.
        return d[start][end];
    if(start == end) { // The mid character should be taken as 
        d[start][end] = 1;
        return 1;
    }
    else if(start == end-1) {
        d[start][end] = (a[start] == a[end])?2:1;
        return d[start][end];
    }
    if(a[start] == a[end]) {
        d[start][end] = max( 2 + computeMaxPalindromeLength(a, start+1, end-1), 
            max(computeMaxPalindromeLength(a, start+1, end), computeMaxPalindromeLength(a, start, end-1)));
    } else {
        d[start][end] = max(computeMaxPalindromeLength(a, start+1, end), computeMaxPalindromeLength(a, start, end-1));
    }
    return d[start][end];
}

Call above method as:-

vector<int>& a; // Convert each character of string to digit if working with alphanumeric characters.
int maxPalindromeLength = computeMaxPalindromeLength(a, 0, a.size()-1);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!