Strings
Strings
Longest Palindrome
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
pairs = set()
counter = 0
for c in s:
if c not in pairs:
pairs.add(c)
elif c in pairs:
pairs.remove(c)
counter += 2
if pairs:
counter += 1
# a string that can't be a palindrome will just return 0
return counter
- Key insight: When working with palindromes, look for a way to track pairs, and one odd character. For this problem, we leverage the notion that valid palindrome has pairs of characters, and at most one non-pair. We use a set to find pairs and if we have one, add two to our counter. At the end, if we have any more characters in our set, just add 1 to our counter. I wasn't sure how leetcode wanted to handle a string that couldn't make a palindrome, but I guess returning 0 makes sense in this context.