409. Longest Palindrome

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.




Idea: 

For each letter, say it occurs v times. We know we have v // 2 * 2 letters that can be partnered for sure. For example, if we have 'aaaaa', then we could have 'aaaa' partnered, which is 5 // 2 * 2 = 4 letters partnered.
At the end, if there was any v % 2 == 1, then that letter could have been a unique center. Otherwise, every letter was partnered. To perform this check, we will check for v % 2 == 1 and ans % 2 == 0, the latter meaning we haven't yet added a unique center to the answer.




class Solution {
    public int longestPalindrome(String s) {
        int res = 0;
        int[] array = new int[128]; // every char has an integer value in ascii table (unicode table)
        // since capitalized letters and lowercased letters are included and they are different , so 
        // here we use int[128], which includes everything , 
        // but if we have only lower case or upper case , we can use int[28], and the pos is x - 'A' or 
        // x - 'a'
        for(char c : s.toCharArray()){
            array[c]++;
        }
        for(int num : array){
            res += num / 2 * 2;
            if(num % 2 == 1 && res % 2 == 0){
                res++;
            }
        }
        return res;
        
    }
}
相關文章
相關標籤/搜索