leetcode1405

第一种方案,使用堆:

 1 from heapq import heappush, heappop
 2 class Solution:
 3     def longestDiverseString(self, a: int, b: int, c: int) -> str:
 4         max_heap = []
 5         if a != 0:
 6             heappush(max_heap, (-a, 'a'))
 7         if b != 0:
 8             heappush(max_heap, (-b, 'b'))
 9         if c != 0:
10             heappush(max_heap, (-c, 'c'))
11         s = []
12         while max_heap:
13             first, char1 = heappop(max_heap) # char with most rest numbers
14             if len(s) >= 2 and s[-1] == s[-2] == char1: # check whether this char is the same with previous two
15                 if not max_heap: # if there is no other choice, just return
16                     return ''.join(s)
17                 second, char2 = heappop(max_heap) # char with second most rest numbers
18                 s.append(char2)
19                 second += 1 # count minus one, because the second here is negative, thus add 1
20                 if second != 0: # only if there is rest number count, add it back to heap
21                     heappush(max_heap, (second, char2))
22                 heappush(max_heap, (first, char1)) # also need to put this part back to heap
23                 continue
24             
25             #  situation that this char can be directly added to answer
26             s.append(char1)
27             first += 1
28             if first != 0:
29                 heappush(max_heap, (first, char1))
30         return ''.join(s)
31         

参考:https://leetcode.com/problems/longest-happy-string/discuss/564248/Python-HEAP-solution-with-explanation

第二种方案,使用递归:

 1 class Solution(object):
 2     def longestDiverseString(self, a, b, c, a_chr="a", b_chr="b", c_chr="c"):
 3         if not (a <= b <= c):
 4             data = sorted([(a, a_chr), (b, b_chr), (c, c_chr)])
 5             return self.longestDiverseString(data[0][0], data[1][0], data[2][0], data[0][1], data[1][1], data[2][1])
 6         if b == 0:
 7             return c_chr * min(2, c)
 8         if b == c:
 9             return c_chr + b_chr + self.longestDiverseString(a, b - 1, c - 1, a_chr, b_chr, c_chr)
10         return c_chr * 2 + b_chr + self.longestDiverseString(a, b - 1, c - 2, a_chr, b_chr, c_chr)

参考:https://leetcode.com/problems/longest-happy-string/discuss/565488/Python-Simple-Recursion

原文地址:https://www.cnblogs.com/asenyang/p/12640547.html