思路
遍历一遍,用hashp来记录每个字母出现的最远位置
maxp代表一个区间的最大位置,t代表区间的初始位置
遍历整个字符串,当遍历到区间的最大位置时,即代表找到一个区间
如:s = “ababcbacadefegdehijhklij” a能到达的最远位置为8 即ababcbaca maxp = 8
从从下标0, b到达最远距离为5,c能到达最远距离为7 均小于a能到达最远的距离,则 下标0-8为一个区间(贪心)
代码
class Solution(object):
def partitionLabels(self, s):
"""
:type s: str
:rtype: List[int]
"""
#记录每个字符出现的最远位置
hashp = {}
res = []
t =0
for i in range(len(s)):
hashp[s[i]]=i
maxp = hashp[s[0]]
for i in range(len(s)):
if i<maxp:
maxp=max(maxp,hashp[s[i]])
if i==maxp:
res.append(i-t+1)
if i<len(s)-1:
t = i+1
maxp=hashp[s[i+1]]
return res