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.
Solution) Count frequencies of all characters. If the number of any character is odd number, finally, it can be used for palindrome by adding one. otherwise, count all other frequencies as even number.
class Solution {
public int longestPalindrome(String s) {
int freq[] = new int['z'-'A'+1];
for (char c : s.toCharArray())
freq[c-'A']++;
boolean odd = false;
int longest = 0;
for (int i=0; i < 'z'-'A'+1; i++) {
if (odd == false && freq[i]%2 == 1) odd = true;
if (freq[i] != 0) longest += freq[i]/2*2;
}
return odd ? longest+1 : longest;
}
}
Another solution is to use hashtable to count odd frequency.
class Solution {
public int longestPalindrome(String s) {
Set<Character> set = new HashSet<>();
for (char c : s.toCharArray()) {
if (set.contains(c)) set.remove(c);
else set.add(c);
}
int odd = set.size();
return s.length() - (odd == 0 ? 0 : odd - 1);
}
}