class Solution:
def longestPalindrome(self, s: str) -> int:
if s is None:
return 0
ans = 0
di = collections.Counter(s)
center = False
for st in di.keys():
if di[st] % 2 == 0:
ans += di[st]
else:
center = True
ans += di[st] // 2 * 2
if center:
ans += 1
return ans
Time complexity is O(n). We need to count each letter. Space complexity is O(1).
class Solution:
"""
@param s: a string which consists of lowercase or uppercase letters
@return: the length of the longest palindromes that can be built
"""
def longestPalindrome(self, s):
# write your code here
if s is None:
return 0
hashTable = set()
ans = 0
for ch in s:
if ch in hashTable:
hashTable.remove(ch)
ans += 2
else:
hashTable.add(ch)
if hashTable:
ans += 1
return ans
Time complexity is O(n). Space complexity is O(1).