题目
同一种题型,思路也是相同的
解题思路
解法一:贪心,每次在都插入当前剩余最多的元素,只有不能继续写入该元素时,才转向另外的元素(仍是剩下中最大的)进行插入。
解法二:插入法,以a = 1, b = 2, c = 7为例
首先构建基础串=“abc(所有元素)” × 1(最少元素对应的数值)+ “bc”(最少数值字母已经用光了,继续用剩下的字母来构造) × 1(第二少元素剩下的数值),最终的基础串为"abcbc" => 用数值最小到数值第二大对应的字母来构建基础串
在基础串中插入剩下的个数的字母,即最后剩下的只有数值最大的字母 => 用数值最大的字母来进行插入操作,插入时保证满足题目要求即可。
但是解法二在处理插入操作的时候,写起来会比较啰嗦,需要大量条件判断当前位置是否能够插入。
代码实现
1405 贪心
"""
1405 贪心
总是每次放入当前剩余个数最多的元素
"""
class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
res, tmp = [], {'a': a, 'b': b, 'c': c}
while max(tmp.values()) > 0:
Flag = False
if len(res) >= 2 and res[-1] == res[-2]:
# 出现了重复,但是没有其他元素可选了
if sum(tmp.values())-tmp[res[-1]] <= 0:
break
Flag = True
# 始终写长的一个
add, max_num = "", float("-inf")
for k, v in tmp.items():
# 如果出现重复,只能在另外两个中选择长的一个
if Flag and k == res[-1]:
continue
if v > max_num:
max_num, add = v, k
tmp[add] -= 1
res.append(add)
return "".join(res)
984 贪心
"""
984 贪心
只有出现相同才转去写另外一个,否则一直写当前长的那个
"""
class Solution:
def strWithout3a3b(self, A: int, B: int) -> str:
res = []
while A or B:
if len(res) >= 2 and res[-1] == res[-2]:
# 出现了两个相同的,就写另外一个
writeA = res[-1] == 'b'
# 没有出现重复or长度不满足的时候,写长的一个
else:
writeA = A >= B
if writeA:
A -= 1
res.append('a')
else:
B -= 1
res.append('b')
return "".join(res)
984 插入法
# 插入法,代码量比较大
class Solution:
def strWithout3a3b(self, A: int, B: int) -> str:
common = min(A, B)
# 首先构造基础串,制造空格位,便于后续插入
s = "a b "*common
add, num = 'a', A-common
if common == A:
add, num = 'b', B-common
s = list(" " + s)
# 将多的插空
for i in range(len(s)):
if not num:
break
if s[i] != " ":
continue
if not i:
if s[2] != add:
s[0] = add
num -= 1
elif i == len(s)-1:
if s[-3] != add:
s[-1] = add
num -= 1
else:
# 左右都和我相同
if s[i-1] == s[i+1] and s[i-1] == add:
continue
# 左边和相同,右边和我不同
if s[i-1] == add and s[i+1] != add:
if s[i-2] == add:
continue
# 右边和我相同,左边和我不同
if s[i+1] == add and s[i-1] != add:
if s[i+2] == add:
continue
# 可以插入
s[i] = add
num -= 1
res = "".join(s).replace(" ", "")
if num:
if s[1] != add:
return add+res
if s[-2] != add:
return res+add
return res