-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path409.py
More file actions
56 lines (40 loc) · 1.39 KB
/
409.py
File metadata and controls
56 lines (40 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return 0
if len(s) == 1:
return 1
from collections import defaultdict
## Get length of each character in the string
## It's either the sum of all the even numbers
## or it's the sum of all the even numbers + longest odd number
character_lengths = defaultdict(lambda: 0)
longest_odd_character_length = 0
longest_odd_character = ''
for i in s:
character_lengths[i] = character_lengths[i] + 1
for i, j in character_lengths.items():
if j % 2 != 0 and j > longest_odd_character_length:
longest_odd_character_length = j
longest_odd_character = i
# print(character_lengths)
# print(longest_odd_character_length)
result = 0
for i,j in character_lengths.items():
if (j % 2 == 0):
result += j
else:
if j >= 1:
if longest_odd_character != i:
result += j - (j % 2)
else:
result += longest_odd_character_length
return result
if __name__ == '__main__':
s = Solution()
#
print(s.longestPalindrome("abccccdd")) # 7