Skip to content

Commit 930a9a4

Browse files
authored
Create longest-happy-string.py
1 parent 21e60f7 commit 930a9a4

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Python/longest-happy-string.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
import heapq
5+
6+
7+
class Solution(object):
8+
def longestDiverseString(self, a, b, c):
9+
"""
10+
:type a: int
11+
:type b: int
12+
:type c: int
13+
:rtype: str
14+
"""
15+
max_heap = []
16+
if a:
17+
heapq.heappush(max_heap, (-a, 'a'))
18+
if b:
19+
heapq.heappush(max_heap, (-b, 'b'))
20+
if c:
21+
heapq.heappush(max_heap, (-c, 'c'))
22+
result = []
23+
while max_heap:
24+
count1, c1 = heappop(max_heap)
25+
if len(result) >= 2 and result[-1] == result[-2] == c1:
26+
if not max_heap:
27+
return "".join(result)
28+
count2, c2 = heappop(max_heap)
29+
result.append(c2)
30+
count2 += 1
31+
if count2:
32+
heapq.heappush(max_heap, (count2, c2))
33+
heapq.heappush(max_heap, (count1, c1))
34+
continue
35+
result.append(c1)
36+
count1 += 1
37+
if count1 != 0:
38+
heappush(max_heap, (count1, c1))
39+
return "".join(result)
40+
41+
42+
# Time: O(n)
43+
# Space: O(1)
44+
class Solution2(object):
45+
def longestDiverseString(self, a, b, c):
46+
"""
47+
:type a: int
48+
:type b: int
49+
:type c: int
50+
:rtype: str
51+
"""
52+
choices = [[a, 'a'], [b, 'b'], [c, 'c']]
53+
result = []
54+
for _ in xrange(a+b+c):
55+
choices.sort(reverse=True)
56+
for i, (x, c) in enumerate(choices):
57+
if x and result[-2:] != [c, c]:
58+
result.append(c)
59+
choices[i][0] -= 1
60+
break
61+
else:
62+
break
63+
return "".join(result)

0 commit comments

Comments
 (0)