-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0791-custom-sort-string.py
More file actions
36 lines (28 loc) · 923 Bytes
/
0791-custom-sort-string.py
File metadata and controls
36 lines (28 loc) · 923 Bytes
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
# time complexity: O(nlogn)
# space complexity: O(n)
from collections import defaultdict
class Solution:
def customSortString(self, order: str, s: str) -> str:
charIdx = {char: idx for idx, char in enumerate(order)}
def customSort(char):
return charIdx.get(char, float('inf'))
sortedString = sorted(s, key=customSort)
return "".join(sortedString)
# time complexity: O(n)
# space complexity: O(1)
class Solution:
def customSortString(self, order: str, s: str) -> str:
freq = defaultdict(int)
for c in s:
freq[c] += 1
result = []
for c in order:
if c in freq:
result.append(c * freq[c])
del freq[c]
for c, count in freq.items():
result.append((c * count))
return ''.join(result)
order = "cba"
s = "abcd"
print(Solution().customSortString(order, s))