Monday, March 16, 2020

LeetCode 409. Longest Palindrome

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

The question is quite easy, and the only caveat when solving this problem is to remember adding back 1 to the answer when we encountered any character with an odd number of occurrences.  For any palindrome, we can add that one character to the middle of the palindrome and still get back a palindrome.


class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
        count = {}
        for i, char in enumerate(s):
            if char in count:
                count[char] += 1
            else:
                count[char] = 1
        ans = 0
        has_odd = False
        for char, k in count.items():
            if k % 2 == 0:
                ans += k
            else: # For those chars with odd number of occurences, we can take an even number of the chars and add them to the palindrome.
                has_odd = True
                ans += k-1
        if has_odd:
            ans += 1
        return ans

No comments:

Post a Comment