字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。
示例 1:
输入:S = “ababcbacadefegdehijhklij” 输出:[9,7,8] 解释: 划分结果为 “ababcbaca”, “defegde”, “hijhklij”。 每个字母最多出现在一个片段中。 像 “ababcbacadefegde”, “hijhklij” 的划分是错误的,因为划分的片段数较少。
提示:
S的长度在[1, 500]之间。 S只包含小写字母 ‘a’ 到 ‘z’ 。
先遍历一遍找到每个字母的左右界 然后从第一个字母往后遍历,当遍历过的字母右界最大值与当前位置重合,就切一份,然后继续遍历切切切,直到最后为止
class Solution: def partitionLabels(self, S: str) -> List[int]: l = {} r = {} ll = len(S) for i in range(ll): if S[i] in l.keys(): r[S[i]]=i else: l[S[i]]=i r[S[i]]=i i = 0 ans = [] maxx = r[S[0]] pre = 0 while i < ll: while i <= maxx: maxx = max(maxx,r[S[i]]) i+=1 if i < ll: maxx = r[S[i]] ans.append(i-pre) pre = i return ans