public class Solution {
public int longestPalindrome(String s) {
int len = 0;
// an integer array to save the frequency of the letters in s
int[] hash = new int[128];
// count the frequency
for (char c : s.toCharArray())
hash[c]++;
// scan the frequency array, add all even numbers and odd numbers minus 1 to len
for (int feq : hash) {
if (feq == 0) continue;
if (feq % 2 == 0)
len += feq;
else
len += feq-1;
}
// if not all feqs are even, put last odd frequency letter in the middle so we need to add 1 to len
// if all feqs are even that is len = s.length() just return len
return (len == s.length()) ? len : len + 1;
}
}
HashSet solution.
public class Solution {
public int longestPalindrome(String s) {
HashSet<Character> hs = new HashSet<Character>();
int pairs = 0;
for (char c : s.toCharArray()) {
if (!hs.add(c)) {
hs.remove(c);
pairs++;
}
}
return (hs.isEmpty()) ? 2*pairs : 2*pairs+1;
}
}