Skip to content

Latest commit

 

History

History
39 lines (30 loc) · 706 Bytes

409. Longest Palindrome.md

File metadata and controls

39 lines (30 loc) · 706 Bytes

409. Longest Palindrome

https://leetcode.com/problems/longest-palindrome/

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

代码

class Solution:
    def longestPalindrome(self, s: str) -> int:
        
        freq = defaultdict(int)
        for ch in s:
            if ch not in freq:
                freq[ch] = 0
            freq[ch] += 1
        
        count = 0

        for ch, v in sorted(freq.items(), key=lambda x:x[1]):
            count += v // 2 * 2
            if count % 2 == 0 and v % 2 == 1:
                count += 1
        
        return count