2086.从房屋收集雨水需要的最少水桶数
一、直接遍历
class Solution:
def minimumBuckets(self, street: str) -> int:
n = len(street)
s = list(street)
for i in range(n):
# 对每个H,优先在其右侧放置B,其次放左侧
if s[i] == 'H':
if i-1 >= 0 and s[i-1] == 'B': #若左侧已有B,跳过
continue
if i+1 < n and s[i+1] == '.':
s[i+1] = 'B'
elif i-1 >= 0 and s[i-1] == '.':
s[i-1] = 'B'
else: #都不符合,直接返回
return -1
cnt = 0
for i in range(n): #最后统计B个数
if s[i] == 'B':
cnt += 1
return cnt
最后更新于