Problem
Given a string s which consists of lowercase or uppercase letters, return the length of the longest
palindrome that can be built with those letters.
Letters are case sensitive, for example, “Aa” is not considered a palindrome.
Algorithm
Count each letter size and sum all the part that multiples of two. If there at least one odd value, the answer plus one.
Code
class Solution:
def longestPalindrome(self, s: str) -> int:
lowercase = [0] * 26
uppercase = [0] * 26
for c in s:
if c >= 'a' and c <= 'z':
lowercase[ord(c) - ord('a')] += 1
if c >= 'A' and c <= 'Z':
uppercase[ord(c) - ord('A')] += 1
ans, odd = 0, 0
for i in range(26):
if lowercase[i] % 2 == 1:
odd = 1
ans += lowercase[i] // 2 * 2
if uppercase[i] % 2 == 1:
odd = 1
ans += uppercase[i] // 2 * 2
return ans + odd