一、问题描述:
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.
二、解决思路:
回文字,这个题目需统计每个元素出现的次数。
用hashmap存放每个元素出现的次数,找出最小的奇数次,其余全部取最大的偶数次数,求和sum。 如果全部的次数都是偶数的话就直接sum
三、实现代码:
public static int longestPalindrome(String s) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < s.length(); i++) {
String tmp = s.charAt(i) + "";
if (map.containsKey(tmp)) {
map.put(tmp, map.get(tmp) + 1);
} else {
map.put(tmp, 1);
}
}
int[] numString = new int[map.size()];
int i = 0;
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
numString[i++] = (int) map.get(iter.next());
}
int minOdd = s.length();
int minOddIndex = 0;
boolean allEven = true;
for (int j = 0; j < map.size(); j++) {
if (numString[j] % 2 != 0) {
minOdd = minOdd < numString[j] ? minOdd : numString[j];
minOddIndex = minOdd < numString[j] ? minOddIndex : j;
allEven = false;
}
}
if (allEven) {
minOdd = 0;
minOddIndex = s.length();
}
int re = minOdd;
for (int j = 0; j < map.size(); j++) {
if (j != minOddIndex) {
re += (numString[j] % 2 == 0) ? numString[j] : numString[j] - 1;
}
}
return re;
}
注: 用allEven指示次数是否全部是偶数次。