class Solution:
def maximumGain(self, s: str, x: int, y: int) -> int:
a = list(s)
if(len(a) < 2): return 0
suma, sumb = 0,0
first = [a[0]]
second = [a[0]]
for i in range(1, len(a)):
if(len(first) > 0 and first[-1] == 'a' and a[i] == 'b'):
del first[-1]
suma += x
else:
first.append(a[i])
if(len(first) > 0):
temp = [first[0]]
for i in range(1,len(first)):
if(len(temp) > 0 and temp[-1] == 'b' and first[i] == 'a'):
del temp[-1]
suma += y
elif(len(temp) > 0 and temp[-1] == 'a' and first[i] == 'b'):
del temp[-1]
sumb += x
else:
temp.append(first[i])
for i in range(1, len(a)):
if(len(second) > 0 and second[-1] == 'b' and a[i] == 'a'):
del second[-1]
sumb += y
else:
second.append(a[i])
if(len(second) > 0):
temp = [second[0]]
for i in range(1,len(second)):
if(len(temp) > 0 and temp[-1] == 'a' and second[i] == 'b'):
del temp[-1]
sumb += x
elif(len(temp) > 0 and temp[-1] == 'b' and second[i] == 'a'):
del temp[-1]
sumb += y
else:
temp.append(second[i])
return max(suma, sumb)
1718. 构建字典序最大的可行序列
Note
dfs递归模拟,写起来还是有些生疏. 没在指定时间写完QAQ
Code
class Solution:
ans = []
flag = 0
def constructDistancedSequence(self, n: int) -> List[int]:
visit = [0] * (n+1)
res = [0] * (2 * n -1)
def dfs(pos, visit, res):
if(pos == 2 * n -1):
self.flag = 1
self.ans = res
return
if(res[pos] > 0):
dfs(pos+1, visit, res)
else:
for i in range(n,0,-1):
if(visit[i] > 0): continue
if(i > 1 and (pos + i >= 2 * n - 1 or res[i + pos] > 0)): continue
visit[i] = 1
res[pos] = i
if(i > 1): res[i + pos] = i
dfs(pos+1,visit,res)
if(self.flag == 1): return
visit[i] = 0
res[pos] = 0
if(i > 1): res[i+pos] = 0
dfs(0,visit,res)
return self.ans