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)