同类问题: 跳跃游戏 跳跃游戏II 视频拼接
问题:
题目来源:力扣(LeetCode)
leetcode763.划分字母区间
难度:中等
分析: 贪心 这道题的思路和跳跃游戏II基本一致。 首先我们需要得到跳跃的步长,即本题中同字符出现的首末位置。然后从第一个字符开始“跳跃”,查找本字符长度区间内其他字符所能到达的最远位置,不断向更远的位置跳跃,直到无法再向后跳跃,说明本区间恰好由几个同种字符(每种字符包含所有个体)构成,为一个合法最小区间。
解决方法: 1:
class Solution:
def
partitionLabels(self
, S: str
) -> List
[int
]:
endList
= [0] * 26
for i
, ch
in enumerate(S):
endList
[ord(ch
) - ord("a")] = i
res
= []
left
= most_right
= 0
for i
, ch
in enumerate(S):
most_right
= max(most_right
, endList
[ord(ch
) - ord("a")])
if i
== most_right
:
res
.append(most_right
- left
+ 1)
left
= most_right
+ 1
return res
转载请注明原文地址: https://lol.8miu.com/read-36655.html