思路一:
-
用字典记录每个字母出现的起始位置。
比如: S = “ababcbacadefegdehijhklij”
得到:{‘a’: [0, 8], ‘b’: [1, 5], ‘c’: [4, 7], ‘d’: [9, 14], ‘e’: [10, 15], ‘f’: [11, 11], ‘g’: [13, 13], ‘h’: [16, 19], ‘i’: [17, 22], ‘j’: [18, 23], ‘k’: [20, 20], ‘l’: [21, 21]} -
参考56、区间合并
得到:[[0, 8], [9, 15], [16, 23]] -
最后计算三个区间的长度
class Solution:
def partitionLabels(self, S: str) -> List[int]:
#记录每个字母起始位置
dict={
}
n=0
for i in S:
if i not in dict:
dict[i]=[n,n]
else:
dict[i][1]=n
n+=1
temp=[]#类似区间合并,暂存区间
for val in dict.values():
if not temp:
temp.append(val)
continue
if val[0]<temp[-1][1]:
temp[-1][1]=max(val[1],temp[-1][1])
else:
temp.append(val)
res=[]
for i in temp:
res.append(i[1]-i[0]+1)
return(res)