Easy
,String
,Greedy
,Hash Table
Given a string s
which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, "Aa"
is not considered a palindrome here.
Input: s = "abccccdd"
Output: 7
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
Input: s = "a"
Output: 1
Explanation: The longest palindrome that can be built is "a", whose length is 1.
Constraints:
class Solution:
def longestPalindrome(self, s: str) -> int:
if len(s) == 1: return 1
ht = defaultdict(int)
for ch in s:
ht[ch] += 1
res = 0
for key, val in ht.items():
res += val // 2 * 2
for key, val in ht.items():
if ht[key] % 2 == 1:
res += 1
break;
return res
Kobe Nov 23, 2022
function longestPalindrome(s) {
const count = [];
for (const char of s) {
if (count[char]) {
count[char]++;
} else {
count[char] = 1;
}
}
let result = 0;
let hasOdd = false;
for (const char in count) {
if (count[char] % 2 === 0) {
result += count[char];
} else {
result += count[char] - 1; // 大於2以上的奇數
hasOdd = true; // 剩下的可以當中間項
}
}
return hasOdd ? result + 1 : result;
}
Marsgoat Nov 29, 2022