Skip to content

Commit f35fcb9

Browse files
committed
Time: 0 ms (100%), Space: 17.7 MB (69.65%) - LeetHub
1 parent 65b3345 commit f35fcb9

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# time complexity: O(a+b+c)
2+
# space complexity: O(1)
3+
from heapq import heappop, heappush
4+
5+
6+
class Solution:
7+
def longestDiverseString(self, a: int, b: int, c: int) -> str:
8+
pq = []
9+
if a > 0:
10+
heappush(pq, (-a, 'a'))
11+
if b > 0:
12+
heappush(pq, (-b, 'b'))
13+
if c > 0:
14+
heappush(pq, (-c, 'c'))
15+
result = []
16+
while pq:
17+
freq, char = heappop(pq)
18+
freq = -freq
19+
if len(result) >= 2 and result[-1] == char and result[-2] == char:
20+
if not pq:
21+
break
22+
tempFreq, tempChar = heappop(pq)
23+
result.append(tempChar)
24+
if tempFreq + 1 < 0:
25+
heappush(pq, (tempFreq + 1, tempChar))
26+
heappush(pq, (-freq, char))
27+
else:
28+
freq -= 1
29+
result.append(char)
30+
if freq > 0:
31+
heappush(pq, (-freq, char))
32+
return "".join(result)
33+
34+
35+
a = 1
36+
b = 1
37+
c = 7
38+
print(Solution().longestDiverseString(a, b, c))

0 commit comments

Comments
 (0)