Skip to main content

2131. Longest Palindrome by Concatenating Two Letter Words

https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/

Python

from collections import Counter


class Solution:
def longestPalindrome(self, words: List[str]) -> int:
counts = Counter(words)

answer = 0
counted = set()
is_center_exists = False

for word, count in counts.items():
# The word can be used as center
if word == word[::-1]:
if count % 2 == 0:
answer += count
else:
answer += count - 1
is_center_exists = True
continue

# Prevent double calculate word already counted ealier
if word in counted:
continue


answer += 2 * min(count, counts[word[::-1]])

# Mark the reverse word is counted
counted.add(word[::-1])

# Every word has length == 2
answer *= 2

# Add 2 for center if its exist
return answer + 2 if is_center_exists else answer