1. 程式人生 > 實用技巧 >0409. Longest Palindrome (E)

0409. Longest Palindrome (E)

Longest Palindrome (E)

題目

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example "Aa" is not considered a palindrome here.

Note:
Assume the length of given string will not exceed 1,010.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

題意

用給定的字元集合組成一個最長的迴文串。

思路

出現次數為偶數的字元全部可以加入迴文串,奇數次的可以-1把偶數部分全部加入,整體只能加一個只出現一次的字元。


程式碼實現

Java

class Solution {
    public int longestPalindrome(String s) {
        int len = 0;
        boolean plusOne = false;
        int[] hash = new int[52];
        for (char c : s.toCharArray()) {
            if (c <= 'Z' && c >= 'A') {
                hash[c - 'A' + 26]++;
            } else {
                hash[c - 'a']++;
            }
        }
        for (int i = 0; i < 52; i++) {
            if (hash[i] > 1 && hash[i] % 2 == 0) {
                len += hash[i];
            } else if (hash[i] > 1) {
                len += hash[i] - 1;
                plusOne = true;
            } else if (hash[i] == 1) {
                plusOne = true;
            }
        }
        return plusOne ? len + 1 : len;
    }
}