leetcode1405

非 Y 不嫁゛ 提交于 2020-04-06 09:47:19

在这三年时间中,做了不少的算法题目,leetcode也已经做到700题了,我觉得差不多了。

虽然和算法的大牛相比还有很大的差距,但对我自己的情况来说,已经算是达到了我的上限水平了。

我不想强求自己的算法能力再进一步提高了。感谢自己这三年的坚持,让我更有信心面对工作中的问题和挑战。

我想我应该抽出时间,对做过的题目,按照类别做一些复习,争取维持现在的算法水平,新的题目就随缘吧。

下面这道题是这周的周赛的一道中等难度的题目,这种题对我来说有点偏难,作为纪念性的第700题,我还是别自己费劲去弄了,参考一下高手的答案吧,哈哈哈。

 

第一种方案,使用堆:

 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!