Solution 1 - Greedy Counting
Use as many character pairs as possible; if any odd remains, place one in the center.
""" 0409.1 - Longest Palindrome - Solution 1 - Greedy Counting """
from collections import Counter
class Solution:
def longestPalindrome(self, s: str) -> int:
c = Counter(s)
res = 0
odd = False
for v in c.values():
res += v // 2 * 2
if v % 2 == 1:
odd = True
return res + (1 if odd else 0)Solution 2 - Running Pair Count
Whenever a char’s count becomes even, add 2 to the answer; at end add 1 if any leftover.
from collections import defaultdict
class Solution:
def longestPalindrome(self, s: str) -> int:
cnt = defaultdict(int)
res = 0
for ch in s:
cnt[ch] += 1
if cnt[ch] % 2 == 0:
res += 2
return res + (1 if res < len(s) else 0)