leetcode解题: Longest Palindrome (409)

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:Hashtable

统计每个字母的出现次数:
若字母出现偶数次,则直接累加至最终结果
若字母出现奇数次,则将其值-1之后累加至最终结果
若存在出现奇数次的字母,将最终结果+1
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char, int> map;
for (char c: s) {
++map[c];
}
int res = 0;
int maxOdd = 0;
int oddSum = 0;
for (auto iter = map.begin(); iter != map.end(); ++iter) {
if (iter->second % 2 == 0) res+= iter->second;
else {
maxOdd = max(iter->second, maxOdd);
oddSum += iter->second - 1;
}
}
if (maxOdd > 0) {
oddSum++;
}
res += oddSum;
return res;
}
};

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public int longestPalindrome(String s) {
if (s == null || s.length() == 0) {
return 0;
}
Map<Character, Integer> map = new HashMap<>();
for (char ch : s.toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
int res = 0;
boolean oddFlag = false;
for (char key : map.keySet()) {
if (map.get(key) % 2 == 0) {
res += map.get(key);
} else {
res += map.get(key) - 1;
oddFlag = true;
}
}
return oddFlag ? res + 1 : res;
}
}