10.22 每日一题 763. 划分字母区间

it2025-08-11  8

字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。 示例 1:

输入:S = "ababcbacadefegdehijhklij" 输出:[9,7,8] 解释: 划分结果为 "ababcbaca", "defegde", "hijhklij"。 每个字母最多出现在一个片段中。 像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。

提示:

S的长度在[1, 500]之间。S只包含小写字母'a'到 'z'。

通过次数24,905 | 提交次数33,809 代码实现

class Solution: def partitionLabels(self, S: str) -> List[int]: lenS = len(S) dic = [0]*26 for i in range(lenS-1,-1,-1): temp = ord(S[i])-ord('a') dic[temp] = max(dic[temp], i) curmax = 0 re = [] before = 0 for i in range(lenS): temp = ord(S[i])-ord('a') if i>curmax: re.append(curmax-before+1) before+=re[-1] curmax = dic[temp] else: curmax = max(curmax, dic[temp]) re.append(curmax-before+1) return re 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/partition-labels 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
最新回复(0)