409. Longest Palindrome

class Solution:
    def longestPalindrome(self, s: str) -> int:
        d = defaultdict(int)
        x = set()
        ans = 0        
        for e in s:
            d[e] += 1
            v = d[e]

            if v == 2:
                ans += 2
                d[e] = 0
                x.remove(e)
            else:
                x.add(e)

        if len(x):
            ans += 1

        return ans

Way 2 :

class Solution:
    def longestPalindrome(self, s: str) -> int:
        c = Counter(s)
        ans = 0
        has = False
        for e in c.values():
            if e % 2 == 0:
                ans += e
            else:
                ans += e - 1
                has = True

        return ans + 1 if has else ans