409.Longest Palindrome === ###### tags: `Easy`,`String`,`Greedy`,`Hash Table` [409. Longest Palindrome](https://leetcode.com/problems/longest-palindrome/) ### 題目描述 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**: * 1 <= s.length <= 2000 * s consists of lowercase and/or uppercase English letters only. ### 解答 #### Python ```python= 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 ``` > [name=Kobe] [time= Nov 23, 2022] #### Javascript ```javascript= 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; } ``` > [name=Marsgoat] [time= Nov 29, 2022] ### Reference [回到題目列表](https://hackmd.io/@Marsgoat/leetcode_every_day)