1405. 最长快乐字符串
如果字符串中不含有任何
'aaa'
,'bbb'
或 'ccc'
这样的字符串作为子串,那么该字符串就是一个「快乐字符串」。给你三个整数
a
,b
,c
,请你返回 任意一个 满足下列全部条件的字符串 s
:s
是一个尽可能长的快乐字符串。
s
中 最多 有a
个字母'a'
、b
个字母'b'
、c
个字母'c'
。
s
中只含有'a'
、'b'
、'c'
三种字母。
如果不存在这样的字符串
s
,请返回一个空字符串 ""
。示例 1:
输入:a = 1, b = 1, c = 7 输出:"ccaccbcc" 解释:"ccbccacc" 也是一种正确答案。
示例 2:
输入:a = 2, b = 2, c = 1 输出:"aabbc"
示例 3:
输入:a = 7, b = 1, c = 0 输出:"aabaa" 解释:这是该测试用例的唯一正确答案。
提示:
0 <= a, b, c <= 100
a + b + c > 0
通过次数27,027提交次数42,212
法1
采用优先队列,优先选择哪些字符较多的字符。当然选择的时候需要判断,当前字符是否和前两个字符均一样,如果一样,那就需要先跳过堆顶。
题解
class Solution: def longestDiverseString(self, a: int, b: int, c: int) -> str: nums = (a, b, c) chars = ("a", "b", "c") # 为了升序排列, 素以对 n 取返 que = [[-n, c] for n, c in zip(nums, chars) if n > 0] heapq.heapify(que) res = [] while que: # 当前储备字符 出队 cur = heapq.heappop(que) # 当前储备不能用 if (len(res) >= 2 and res[-1] == cur[1] and res[-2]==cur[1]): # 当前储备不能上,则下一个储备一定能上 # 判断还有无下一个储备 if not que: break # 下一个储备出队,且放一个字符到结果中 next_ = heapq.heappop(que) res.append(next_[1]) # 如果还有剩余,还能入队 next_[0] = -((-next_[0]) - 1) if next_[0] != 0: heapq.heappush(que, next_) # 因为当前的储备没用上,所以再存回去 heapq.heappush(que, cur) # 当前的储备能上 else: res.append(cur[1]) cur[0] = -((-cur[0]) - 1) if cur[0] != 0: heapq.heappush(que, cur) return ''.join(res)