leetcode-1405. 最长快乐字符串

1405. 最长快乐字符串
如果字符串中不含有任何 'aaa','bbb' 或 'ccc' 这样的字符串作为子串,那么该字符串就是一个「快乐字符串」。

给你三个整数 a,b ,c,请你返回 任意一个 满足下列全部条件的字符串 s:

s 是一个尽可能长的快乐字符串。
s 中 最多 有a 个字母 'a'、b 个字母 'b'、c 个字母 'c' 。
s 中只含有 'a'、'b' 、'c' 三种字母。
如果不存在这样的字符串 s ,请返回一个空字符串 ""。

 

1. 递归构建 [超时]

class Solution:
    def longestDiverseString(self, a: int, b: int, c: int) -> str:
    
        res = ""
        

        def deep(a, b, c, string):
            nonlocal res
            if len(string) > len(res):
                res = string
            
            if a > 0:
                if len(string) >= 2 and string[-1] == 'a' and string[-2] == 'a':
                    pass
                else:
                    deep(a - 1, b, c, string + 'a')

            if b > 0:
                if len(string) >= 2 and string[-1] == 'b' and string[-2] == 'b':
                    pass
                else:
                    deep(a, b-1, c, string + 'b')

            if c > 0:
                if len(string) >= 2 and string[-1] == 'c' and string[-2] == 'c':
                    pass
                else:
                    deep(a, b, c-1, string + 'c')
            
        deep(a, b, c, "")
        return res

2. 贪心

减少了每一层级遍历情况

class Solution:
    def longestDiverseString(self, a: int, b: int, c: int) -> str:
        ans = []
        cnt = [[a, 'a'], [b, 'b'], [c, 'c']]
        while True:
            cnt.sort(key=lambda x: -x[0])
            hasNext = False
            for i, (c, ch) in enumerate(cnt):
                if c <= 0:
                    break
                if len(ans) >= 2 and ans[-2] == ch and ans[-1] == ch:
                    continue
                hasNext = True
                ans.append(ch)
                cnt[i][0] -= 1
                break
            if not hasNext:
                return ''.join(ans)


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值