-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestPalindrome
More file actions
35 lines (31 loc) · 1.19 KB
/
LongestPalindrome
File metadata and controls
35 lines (31 loc) · 1.19 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
#Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
#Letters are case sensitive, for example, "Aa" is not considered a palindrome here.
class Solution:
def longestPalindrome(self, s: str) -> int:
s_dict = {}
for i in s:
if i in s_dict.keys():
s_dict[i] += 1
else:
s_dict[i] = 1
palindrome_length = 0
greatest_odd_letter = 0
for key in s_dict:
if s_dict[key] % 2 == 0:
palindrome_length += s_dict[key]
if s_dict[key] % 2 != 0:
palindrome_length += s_dict[key] - 1
if s_dict[key] > greatest_odd_letter:
greatest_odd_letter = s_dict[key]
if greatest_odd_letter >= 1:
palindrome_length += 1
return palindrome_length
##Use python collections data storage
class Solution:
def longestPalindrome(self, s):
ans = 0
for v in collections.Counter(s).itervalues():
ans += v / 2 * 2
if ans % 2 == 0 and v % 2 == 1:
ans += 1
return ans