Runtime: 35 ms, faster than 5.55% of Java online submissions for Longest Palindrome. Memory Usage: 42.2 MB, less than 64.86% of Java online submissions for Longest Palindrome.
class Solution {
public int longestPalindrome(String s) {
int result = 0;
int maxOdd = 0;
Map<Character, Integer> map = new HashMap<>();
for(int i=0; i<s.length(); i++) {
if(map.containsKey(s.charAt(i))) {
int val = map.get(s.charAt(i));
val = val + 1;
map.put(s.charAt(i), val);
} else {
map.put(s.charAt(i), 1);
}
}
boolean odds = false;
for(int i=0; i<s.length(); i++) {
if(map.get(s.charAt(i)) == null) {
continue;
}
int val = map.get(s.charAt(i));
if(val % 2 == 0) {
// sum the pairs
result = result + val;
map.remove(s.charAt(i));
} else {
// sum the odds a pair
odds = true;
result = result + val - 1;
map.remove(s.charAt(i));
}
}
// if we ever added an odd we must add a extra 1
return result + (odds ? 1 : 0);
}
}