Back to course home
0% completed
Vote For New Content
python solution, using the "odd_detected" flag
Modestas Filipavicius
Dec 24, 2025
class Solution: def longestPalindrome(self, s: str) -> int: length = 0 # count all the chars ct = {} for c in s: ct[c] = ct.get(c, 0) + 1 # flag counter to see how many odd counts detected odd_detected = 0 # traverse the set of chars for char in set(s): if ct[char] % 2 == 0: # even count, increment length length += ct[char] elif ct[char] % 2 == 1 and ct[char] > 2: # odd count is > 2, tally up as if it was odd count, but increment the flag # needed when s = 'xxxyyy' length += ct[char] - 1 odd_detected += 1 else: # odd count == 1, increment flag # needed when s = 'abcde' odd_detected += 1 # check if any odds found, and increment length by one if odd_detected > 0: length += 1 return length
0
0
Comments
Comments