前缀和是不是相当于dp啊?
思路其实比较明显就是
1:找到最靠近queries[left]右蜡烛和最靠近queries[right]的左蜡烛;
2:计算两个蜡烛之间的盘子数。
对于第一个问题可以采用二分,也可以正反扫描一次然后把每个蜡烛最近的盘子索引维护一个一维列表
对于第二个问题就采用前缀和。即每个蜡烛都记录到自己为止所经过的盘子数,相减即得(所以这个算不算dp的范围呢)
class Solution(object):
def platesBetweenCandles(self, s, queries):
"""
:type s: str
:type queries: List[List[int]]
:rtype: List[int]
感觉挺简单的试一下
二分查找?是的,也可以前缀和
"""
list_temp=[]
ans=[]
temp_l=-1
temp_r=len(s)
count=0
for i in range(len(s)):
if s[i]=='*':
list_temp.append([temp_l])
count+=1
else:
list_temp.append(count)
temp_l=i
for i in range(len(s)):
if s[len(s)-1-i]=='*':
list_temp[len(s)-1-i].append(temp_r)
else:
temp_r=len(s)-1-i
for start,end in queries:
if s[start]=='*':
start=list_temp[start][1]
if s[end]=='*':
end=list_temp[end][0]
if start>=end:
ans.append(0)
else:
ans.append(list_temp[end]-list_temp[start])
return ans