Sunday, April 14, 2019

Lintcode 627. 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.

Example

Example 1:
Input : s = "abccccdd"
Output : 7
Explanation :
One longest palindrome that can be built is "dccaccd", whose length is `7`.

Notice

Assume the length of given string will not exceed 1010.
Code (Java):
public class Solution {
    /**
     * @param s: a string which consists of lowercase or uppercase letters
     * @return: the length of the longest palindromes that can be built
     */
    public int longestPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        
        int[] counts = new int[52];
        
        for (char c : s.toCharArray()) {
            if (Character.isLowerCase(c)) {
                counts[c - 'a']++;
            } else {
                counts[c - 'A' + 26]++;
            }
        }
        
        int ans = 0;
        boolean hasOdd = false;
        
        for (int count : counts) {
            ans += count / 2;
            if (count % 2 == 1) {
                hasOdd = true;
            }
        }
        
        ans *= 2;
        if (hasOdd) {
            ans += 1;
        }
        
        return ans;
    }
}

No comments:

Post a Comment