-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorganiseString.py
More file actions
33 lines (28 loc) · 1.15 KB
/
Copy pathReorganiseString.py
File metadata and controls
33 lines (28 loc) · 1.15 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
class Solution:
def reorganizeString(self, s: str) -> str:
#Creating character set frequency list
freq_list = [0] * 26
for char in s:
freq_list[ord(char) - ord('a')] += 1
# Sort the characters in decreasing order of their frequencies
sorted_chars = []
for i in range(26):
if freq_list[i] > 0:
sorted_chars.append(chr(i + ord('a')))
sorted_chars.sort(key=lambda x: (-freq_list[ord(x) - ord('a')], x))
#Check if the most frequent character has a frequency greater than half of the string length
if freq_list[ord(sorted_chars[0]) - ord('a')] > (len(s) + 1) // 2:
return ""
# Initialize the result string
result = [""] * len(s)
# Fill the result string with alternating characters
idx = 0
for char in sorted_chars:
while freq_list[ord(char) - ord('a')] > 0:
result[idx] = char
idx += 2
if idx >= len(s):
idx = 1
freq_list[ord(char) - ord('a')] -= 1
# Return the result string
return "".join(result)