# 7 lines java solution with explanation (22ms)

1. use a map to get counts of each of the characters .
2. go thru the map and add up the closest even number that equals or is smaller than the count. (if we see even number, we take it, if we see odd number, we can take the closest smaller even number to it).
3. we return the smaller number between the length of the string and the result from step2 + 1 , why ? because if all the numbers we seen previously are even, then the entire string is a valid return result, if that is not the case, there must exist odd numbers, it doesn't matter how many of them we have in there, as we have already collected the even part of all the numbers, we just put any of the characters that have odd count of appearance in the middle to compose the palindrome, therefore add ONE to the sum of even counts.
``````  public int longestPalindrome(String s) {
Map<Character,Integer> map = new HashMap<>();
for (char c : s.toCharArray()) {
map.put(c,map.getOrDefault(c, 0)+1);
}
int returnVal = 0 ;
for (char c : map.keySet()) {
returnVal += map.get(c)/2 * 2;
}
return Math.min(returnVal+1, s.length());
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.