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.
思路:统计词频,然后偶数都可以加进去,没问题,统计奇数的个数,奇数可以取val-1个,然后最后,如果有奇数的,那么就可以多加一个1,因为可以以奇数为核心。
class Solution {
public int longestPalindrome(String s) {
HashMap<Character, Integer> hashmap = new HashMap<>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
hashmap.put(c, hashmap.getOrDefault(c, 0) + 1);
}
int count = 0;
boolean findodd = false;
for(Character key: hashmap.keySet()) {
if(hashmap.get(key) % 2 == 0) {
count += hashmap.get(key);
} else {
findodd = true;
count += hashmap.get(key) / 2 * 2;
}
}
if(findodd) {
count++;
}
return count;
}
}