# time O(N) space O(K) since alphabetic but technically O(lgN)
import collections
class Solution:
def longestPalindrome(self, s: str) -> int:
d = collections.Counter(s)
cnt = 0
odd = False
for c in d.keys():
if d[c] >= 2:
cnt += d[c]//2 * 2
if d[c] % 2 == 1:
odd = True
return cnt+1 if odd else cnt
collectiosn.Counter() can accept string, mapping{‘a’:12,’b’:2} and argument (a=2,b=3) as arguments reverse logic: to count odd number, and use len(s) -odd and give additional 1 given if odd exist
class Solution:
def longestPalindrome(self, s: str) -> int:
d = collections.Counter(s)
odds = 0
for k,v in d.items():
odds += v%2
return len(s) - odds + 1 if odds >= 1 else len(s) - odds # len(s) -odds + bool(odds)
to further reduce space can use set structure, but will time complexity increases.