Skip to content
LC-0409 Easy LeetCode

409. Longest Palindrome

Read the full problem statement on LeetCode.
Difficulty: easy Acceptance: 56% Topics: Hash Table, String, Greedy
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(1)

import collections


class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
        odds = 0
        for k, v in collections.Counter(s).iteritems():
            odds += v & 1
        return len(s) - odds + int(odds > 0)

    def longestPalindrome2(self, s):
        """
        :type s: str
        :rtype: int
        """
        odd = sum(map(lambda x: x & 1, collections.Counter(s).values()))
        return len(s) - odd + int(odd > 0)

Solution from kamyu104/LeetCode-Solutions · MIT