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.

Solution:

A character's count is even number, we can add all of them into the palindrome; if it is odd, we can add n - 1 into the palindrome. However, even if we have more than one character with odd count, we can only add one to the palindrome to make the total count an odd number. Use a hash set to monitor the count of all letters, if it reaches 2, add both to the count, and remove the one in the set. In the end, return count + 1 if there is any letters remained in the hash set, or count if the hash set is empty.

public int longestPalindrome(String s) {
    if (s == null || s.length() == 0) {
        return 0;
    }
    HashSet<Character> set = new HashSet<>();
    int count = 0;
    for (char c : s.toCharArray()) {
        if (set.contains(c)) {
            set.remove(c);
            count += 2;
        } else {
            set.add(c);
        }
    }
    if (!set.isEmpty()) {
        return count + 1;
    }
    return count;
}

results matching ""

    No results matching ""