Longest Palindrome by Concatenating Two Letter Words LeetCode solution in Python

1
class Solution(object):
2
def longestPalindrome(self, words):
3
wc = collections.Counter(words)
4
aa = 0 # count how many words contain only two identical letters like 'aa'
5
center = 0 # if one count of 'aa' is odd, that means it can be the center of the palindrome, answer can plus 2
6
abba = 0 # count how many word pairs like ('ab', 'ba') and they can put on both sides respectively
7

8
for w, c in wc.items():
9
if w[0] == w[1]: # like 'aa', 'bb', ...
10
aa += (
11
c // 2 * 2
12
) # if there are 3 'aa', we can only use 2 'aa' put on both sides respectively
13
# if one count of 'aa' is odd, that means it can be the center of the palindrome, answer can plus 2
14
if c % 2 == 1:
15
center = 2
16
else:
17
abba += min(wc[w], wc[w[::-1]]) * 0.5 # will definitely double counting
18
return aa * 2 + int(abba) * 4 + center

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0