LeetCode 409. 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.

解题思路

这道题的解题关键是不要把它想复杂!仔细观察回文串,所有双数出现的字符是不是都可以被放入回文里?答案是肯定的。单数出现的呢?只能有一个。那么其他的单数出现只能被丢弃一个变为偶数。这就是贪心性质。

代码

class Solution:
    def longestPalindrome(self, s: str) -> int:
        d = collections.defaultdict(int)
        for i in s:
            d[i] += 1
        ans = 0
        flag = True
        for c in d.keys():
            if d[c] % 2 == 0:
                ans += d[c]
            elif flag == True:
                flag = False
                ans += d[c]
            else:
                ans += d[c] - 1
        return ans

你可能感兴趣的:(LeetCode,leetcode,算法,职场和发展)