409. Longest Palindrome

Tapan RachchhTapan Rachchh
1 min read
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
0
Subscribe to my newsletter

Read articles from Tapan Rachchh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tapan Rachchh
Tapan Rachchh