Re: [闲聊] 每日leetcode

楼主: DJYOMIYAHINA (通通打死)   2024-07-12 23:33:02
一开始想用DP
干发现怎么都D不太出来:(
后来发现好像不管先碰ab或先碰ba,最后总共碰的次数都会一样
(不会因为某个地方选择碰ba不碰ab,造成后面总共碰的对数少了几对)
总而言之就变成说
若y>x,就先全碰ba,最后再来处理ab
反之就先全碰ab,最后再来处理ba
大概是这样
写得丑丑:(
def maximumGain(self, s: str, x: int, y: int) -> int:
stk = []
score = 0
for c in s:
if x >= y:
if stk and stk[-1] == 'a' and c == 'b':
stk.pop()
score += x
else:
stk.append(c)
else:
if stk and stk[-1] == 'b' and c == 'a':
stk.pop()
score += y
else:
stk.append(c)
stk2 = []
for c in stk:
if stk2 and stk2[-1] == 'a' and c == 'b':
stk2.pop()
score += x
elif stk2 and stk2[-1] == 'b' and c == 'a':
stk2.pop()
score += y
else:
stk2.append(c)
return score
作者: Sadolapapa (凛)   2024-07-12 23:39:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com