A palindrome reads the same forwards and backwards. For most characters, we need pairs: one for each side. Characters with even counts can be fully used. Characters with odd counts contribute their largest even portion, and at most one odd character can sit in the middle. We count character frequencies and sum up pairs as we find them.
result to 0.2 to the result (a new pair formed).1 for the middle position.Where is the length of the given string, and is the number of distinct characters in the string.
We can simplify the check for the middle character. If the total count of paired characters is less than the string length, it means at least one character has an odd count, so we can place one in the middle. This eliminates the need for a separate loop to check for odd counts.
result < length of string, add 1 (there's a leftover character for the middle).Where is the length of the given string, and is the number of distinct characters in the string.
Instead of counting exact frequencies, we only need to know if a character has been seen an odd number of times. A set works perfectly: add a character when first seen, remove it when seen again (forming a pair). Each removal represents a pair. At the end, if the set is non-empty, we can use one character as the center.
result to 0.2 to result (pair completed).1 to result.Where is the length of the given string, and is the number of distinct characters in the string.
Since we're only dealing with lowercase and uppercase English letters (52 total), we can use two 32-bit integers as bitmasks instead of a set. Each bit represents whether that character has been seen an odd number of times. Toggling a bit (XOR) when we see a character tracks odd/even status. When a bit flips from 1 to 0, we found a pair.
a-z), one for uppercase (A-Z).2 to result (pair formed).1 for the middle.class Solution:
def longestPalindrome(self, s: str) -> int:
mask1 = 0 # [a - z]
mask2 = 0 # [A - Z]
res = 0
for c in s:
if 'a' <= c <= 'z':
bit = 1 << (ord(c) - ord('a'))
if mask1 & bit:
res += 2
mask1 ^= bit
else:
bit = 1 << (ord(c) - ord('A'))
if mask2 & bit:
res += 2
mask2 ^= bit
return res + 1 if mask1 or mask2 else resA common mistake is forgetting that a palindrome can have one character with an odd count placed in the center. After counting all pairs, you must check if any character has a leftover (odd count) and add 1 to the result if so. Without this, you will undercount the length for strings like "abcba" where "c" can be the center.
The problem distinguishes between uppercase and lowercase letters ('A' and 'a' are different characters). A frequent error is treating them as the same character or forgetting to handle both cases. Make sure your counting logic accounts for the full character set specified in the problem constraints.