Python 4 lines solution


  • 0
    A
    def longestPalindrome(self, s):
        # Need to import "collections" library.
        # Sum all even occurrences.
        evenSum = sum(count for count in collections.Counter(s).values() if count % 2 == 0)
        # Convert all odd occurences to even and sum. 
        # We need to add 1 at last because we can put a single letter at the middle.
        convertOddSumToEvenSum = sum(count-1 for count in collections.Counter(s).values() if count % 2 == 1)
        # Check whether the string only contains letters that have even occurances
        oddSum = sum(count for count in collections.Counter(s).values() if count % 2 == 1)
        return evenSum + convertOddSumToEvenSum + 1 if oddSum != 0 else evenSum

Log in to reply
 

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