A string is called happy if it does not have any of the strings 'aaa'
, 'bbb'
or 'ccc'
as a substring.
Given three integers a
, b
and c
, return any string s
, which satisfies following conditions:
s
is happy and longest possible.s
contains at mosta
occurrences of the letter'a'
, at mostb
occurrences of the letter'b'
and at mostc
occurrences of the letter'c'
.s
will only contain'a'
,'b'
and'c'
letters.
If there is no such string s
return the empty string ""
.
Example 1:
Input: a = 1, b = 1, c = 7 Output: "ccaccbcc" Explanation: "ccbccacc" would also be a correct answer.
Example 2:
Input: a = 2, b = 2, c = 1 Output: "aabbc"
Example 3:
Input: a = 7, b = 1, c = 0 Output: "aabaa" Explanation: It's the only correct answer in this case.
Constraints:
0 <= a, b, c <= 100
a + b + c > 0
思路:贪心,优先队列
class Solution(object):
def longestDiverseString(self, a, b, c):
"""
:type a: int
:type b: int
:type c: int
:rtype: str
"""
import heapq
pq = [(-a,'a'), (-b,'b'), (-c,'c')]
pq = [s for s in pq if s[0]<0]
heapq.heapify(pq)
res = []
while pq:
s,c = heapq.heappop(pq)
if len(res)>=2 and c==res[-1] and c==res[-2]:
if not pq:
break
else:
s2,c2 = heapq.heappop(pq)
res.append(c2)
if -s2-1>0:
heapq.heappush(pq, (s2+1,c2))
heapq.heappush(pq, (s,c))
else:
res.append(c)
if -s-1> 0:
heapq.heappush(pq, (s+1,c))
return ''.join(res)
s=Solution()
print(s.longestDiverseString(a = 1, b = 1, c = 7))