2-line python solution


  • 0
    F

    x & (~1) gives the maximum even number not larger than x.

    def longestPalindrome(self, s):
        cnt = collections.Counter(s)
        return sum(cnt[n] & (~1) for n in cnt) + int(any(cnt[n] % 2 for n in cnt))
    

  • 1

    I came up with a similar solution. Since you don't need the dictionary keys you can simplify the second line like this:

    def longestPalindrome(self, s):
        cnt = collections.Counter(s).values()
        return sum(i&~1 for i in cnt) + any(i%2 for i in cnt)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.