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:先直接把字符数v加到length上,再判断v的奇偶性,如果偶数就不用管了,如果是奇数就减个1,同时标记一下values中有奇数.因为前面的奇数的情况,我们每次都只加偶数个(即是v-1个),所以在最后我们要做一下处理.我的做法是,如果我们的字符数集合中有奇数(即hasOdd为true),我就让结果+1,这个意思就是取任意一个奇数个字符的字符放在回文字符串的中间位置.这个是我自己的解法,感觉思路不是那么清晰.看了别人的解法,感觉很清晰,见解法2
public int longestPalindrome(String s) {
HashMap<Character, Integer> palindromeMap = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
palindromeMap.put(ch, palindromeMap.getOrDefault(ch, 0)+1);
}
Collection<Integer> values = palindromeMap.values();
int length = 0; boolean hasOdd = false;
for (int v : values) {
length += v;
if (v%2 == 1) {
hasOdd = true;
length -= 1;
}
}
return hasOdd? length+1 : length;
}
解法2:分类讨论,对回文字符长度的奇偶性做讨论.不论某个字符的个数是奇数个还是偶数个,都只取偶数个.如果当前回文字符串长度为偶数个,同时某个字符的个数为奇数个,则将该字符放回文串的中间,对length做+1的操作.
public static int longestPalindrome(String s) {
HashMap<Character, Integer> palindromeMap = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
palindromeMap.put(ch, palindromeMap.getOrDefault(ch, 0)+1);
}
Collection<Integer> values = palindromeMap.values();
int length = 0;
for (int v : values) {
length += v/2*2;
if (length%2 == 0 && v%2 == 1) length ++;
}
return length;
}