题:https://leetcode.com/problems/longest-palindrome/description/
题目
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.
题目大意
计算一组字符集合可以组成的回文字符串的最大长度
思路
1.计算 字符串中,每个字符的 对数。在回文字符中,成对的数放入。
2.若由字符对数 组成的 回文字符 长度小于 原字符串,则 可以有个单独字符 作为 回文串的中心。
class Solution {
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 res = 0;
int center = 0;
for(char c : map.keySet()){
res += map.get(c)/2;
}
res = res<<1;
if(res<s.length())
res++;
return res;
}
}