地里新农-请到考试中心学习规则
- 积分
- 0
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2019-9-5
- 最后登录
- 1970-1-1
|
这道题可以用DP O(n)的算法来解决,画了一个图,放在附件里了
用两个数组d1和d2,分别记录从开始到整个字符串里每个字符的*的个数, 和从最后一个位置到之前每个位置的*的个数。“*”的个数可以用下面的公式直接算出来,不用遍历。 num = d1[-1] - d1[start] - d2[end] .
python 的代码如下:- def numberOfItems(s, startIndices, endIndices):
- # Write your code here
- res = []
- d1 = []
- d2 = []
- count = 0
- i = 0
- size = len(s) - 1
- while s[size] == '*':
- size -= 1
- while s[i] == '*':
- i += 1
- d1.append(0)
- while i < size + 1:
- if s[i] == '*':
- count += 1
- d1.append(count)
- elif s[i] == '|':
- d1.append(count)
- i += 1
- d2 = [count - i for i in d1]
- for i in range(len(startIndices)):
- start, end = startIndices[0]-1, endIndices[0]-1
- while s[start] == '*':
- start += 1
- while s[end] == '*':
- end -= 1
- res.append(count - d1[start] - d2[end])
- return res
- s = "*|***|****|*****|**"
- startIndices = [1, 1]
- endIndices = [10, 11]
- print (numberOfItems(s, startIndices, endIndices))
复制代码 |
本帖子中包含更多资源
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
|