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.思路:
编译好几次不过,注意几个问题,最大奇数字母长度全部加进去,其他奇数字母加上偶数部分。
int upperNum[] = new int[26];
int lowerNum[] = new int[26];
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) - 'a' >= 0) {
lowerNum[s.charAt(i) - 'a']++;
} else {
upperNum[s.charAt(i) - 'A']++;
}
}
int maxSingle = 0;
int len = 0;
for (int i = 0; i < lowerNum.length; i++) {
if (lowerNum[i] == 0)
continue;
if (lowerNum[i] % 2 == 0) {
len += lowerNum[i];
} else {
if (lowerNum[i] > maxSingle) {
len += maxSingle - 1;
maxSingle = lowerNum[i];
} else
len += lowerNum[i] - 1;
}
}
for (int i = 0; i < upperNum.length; i++) {
if (upperNum[i] == 0)
continue;
if (upperNum[i] % 2 == 0) {
len += upperNum[i];
} else {
if (upperNum[i] > maxSingle) {
len += maxSingle - 1;
maxSingle = upperNum[i];
} else
len += upperNum[i] - 1;
}
}
return (maxSingle == 0) ? len : len + maxSingle + 1;
Set:
public class Solution {
public int longestPalindrome(String s) {
Set<Character> set = new HashSet<>();
int count = 0;
for (char c : s.toCharArray()) {
if (set.contains(c)) {
set.remove(c);
count += 2;
} else {
set.add(c);
}
}
return count + (set.size() > 0 ? 1 : 0);
}
}