A string s
is called happy if it satisfies the following conditions:
s
only contains the letters'a'
,'b'
, and'c'
.s
does not contain any of"aaa"
,"bbb"
, or"ccc"
as a substring.s
contains at mosta
occurrences of the letter'a'
.s
contains at mostb
occurrences of the letter'b'
.s
contains at mostc
occurrences of the letter'c'
.
Given three integers a
, b
, and c
, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string ""
.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: a = 1, b = 1, c = 7 Output: "ccaccbcc" Explanation: "ccbccacc" would also be a correct answer.
Example 2:
Input: a = 7, b = 1, c = 0 Output: "aabaa" Explanation: It is the only correct answer in this case.
Constraints:
0 <= a, b, c <= 100
a + b + c > 0
题目说一个字符串s可以被称为快乐字符串需要满足以下条件:
s
只含有字母'a'
,'b'
, and'c'
.s
中相同字母连续不超过2个,即不含有任何"aaa"
,"bbb"
, or"ccc"
子字符串.s
包含字母'a'个数最多不超过整数a
.s
包含字母'b'
.个数最多不超过整数bs
包含字母'c'个数最多不超过整数c
现在给定3个整数a,b和c,要求返回由它们组成的最长的欢乐字符串。
解题思路:属于重组字符串的题,跟767. Reorganize String有一点像,原则是使相同字母每隔一个位置放两个使得连续的相同字母不超过2个,另外本着在前面尽可能地多取字母放入字符串的原则,因此每次要从个数最多的字母中(如果大于两个的话)取出两个放入字符串中,紧随其后应该取其它的字母这样才不至于连续相同字母大于等于3,那其它字母应该取一个还是两个呢?还是本着尽可能优先处理字母个数最多的字母的原则,如果第一次被取走2个的字母剩下个数还是最多的,那么就从第二多的字母中取出一个放入字符串以做隔离以便下次还是取2个最多的字母;如果第一次被取走2个的字母剩下个数就不是最多的了,那么原来第二多的就变成最多的了,那就应该取出2个放入字符串中。如此循环下去,当字母种类只剩一种时就应该停止循序,最后再放入2个剩下的字母。这样组成的字符串就是最长的。
class MyChar:
def __init__(self, c, n):
self.c = c
self.n = n
def __lt__(self, other):
return self.n > other.n
class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
pq = []
if a > 0:
heapq.heappush(pq, MyChar('a', a))
if b > 0:
heapq.heappush(pq, MyChar('b', b))
if c > 0:
heapq.heappush(pq, MyChar('c', c))
res = []
while len(pq) > 1:
c1 = heapq.heappop(pq)
res.append(c1.c)
c1.n -= 1
if c1.n > 0:
res.append(c1.c)
c1.n -= 1
c2 = heapq.heappop(pq)
if c1.n >= c2.n:
res.append(c2.c)
c2.n -= 1
if c1.n > 0:
heapq.heappush(pq, c1)
if c2.n > 0:
heapq.heappush(pq, c2)
while len(pq) > 0:
c1 = heapq.heappop(pq)
res.append(c1.c)
c1.n -= 1
if c1.n > 0:
res.append(c1.c)
break
return ''.join(res)