1405. Longest Happy String

18 篇文章 0 订阅
16 篇文章 0 订阅

A string is called happy if it does not have any of the strings 'aaa''bbb' or 'ccc' as a substring.

Given three integers ab and c, return any string s, which satisfies following conditions:

  • s is happy and longest possible.
  • s contains at most a occurrences of the letter 'a'at most b occurrences of the letter 'b' and at most c occurrences of the letter 'c'.
  • 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))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值