LeetCode 409-- longest palindromic sequence

1. Topic

2. Answers

Let's look at the law palindromic substring, if palindromic substring length is even, in which all of each element appears even number; if the palindromic substring length is odd, there is an odd element appears times and each of the remaining elements appear even number of times.

So we need to do is to walk again string, count the number of each element appears. There's only uppercase and lowercase letters, we use an array of size 52 can act as a hash table.

Finally, we can draw an even number of elements of how many, and then see if there is a surplus of odd elements get the longest palindromic sequence can be composed of.

int longestPalindrome(string s) {

    int n = s.size();
    if (n == 0) return 0;
    int table[52] = {0};
        
    for (int i = 0; i < n; i++)
    {
        int index = int(s[i] - 'A');
        if (s[i] >= 'a')    index -= 6;
        table[index]++;
    }

    int even = 0;
    int odd = 0;
    for (int i = 0; i < 52; i++)
    {
        even += table[i] / 2 * 2;
        odd += table[i] % 2;     
    }
    
    odd = odd > 0 ? 1: 0;
    return even + odd;
}

For more exciting, please pay attention to "seniusen"!

Guess you like

Origin www.cnblogs.com/seniusen/p/11991140.html