-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path2384-largest-palindromic-number.py
More file actions
40 lines (31 loc) · 1.05 KB
/
2384-largest-palindromic-number.py
File metadata and controls
40 lines (31 loc) · 1.05 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
# time complexity: O(n)
# space complexity: O(n)
from typing import Counter
class Solution:
def largestPalindromic(self, num: str) -> str:
freq = Counter(num)
firstHalf = []
middle = ""
for digit in range(9, -1, -1):
digitChar = str(digit)
if digitChar in freq:
digitCount = freq[digitChar]
numPairs = digitCount // 2
if numPairs:
if not firstHalf and not digit:
freq['0'] = 1
else:
firstHalf.append(digitChar * numPairs)
if digitCount % 2 and not middle:
middle = digitChar
if not middle and not firstHalf:
return "0"
return "".join(firstHalf + [middle] + firstHalf[::-1])
num = "444947137"
print(Solution().largestPalindromic(num))
num = "00009"
print(Solution().largestPalindromic(num))
num = "00001105"
print(Solution().largestPalindromic(num))
num = "00011"
print(Solution().largestPalindromic(num))