[Leetcode] 763. Partition Labels

763. Partition Labels (题目链接)

Medium

A string S of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.

 

Example 1:

Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.

 

Note:

  • S will have length in range [1, 500].
  • S will consist of lowercase English letters ('a' to 'z') only.

 

思路:

这个题要进行字符串的分段,分段的标准是,这个段里面的字符串不会再出现在其他的字符串中。要求是尽可能的分成更多的串,最后的返回结果是这些串的长度组成的一个数组。

我们从第一个字母开始,统计每个字母出现最远位置的索引,因为一个字母可能出现多次,我们先遍历一遍整个S,找出这个字母出现位置最大的索引,然后放到一个dict里面。比如上面的例子, 我们计算出来的结果是下面这样的。

{'a': 8, 'b': 5, 'c': 7, 'd': 14, 'e': 15, 'f': 11, 'g': 13, 'h': 19, 'i': 22, 'j': 23, 'k': 20, 'l': 21}

我们接着再遍历一遍整个S,用一个变量存在当前经过的最大索引,一个变量记录当前段的开始索引,当当前字母的索引等于当前最大索引的时候,整个段结束,计算长度,存入结果数组里,然后将记录开始索引的变量置为下一个索引。

import collections
class Solution:
    def partitionLabels(self, S: str) -> List[int]:
        index = collections.defaultdict(int)
        for i in range(len(S)):
            index[S[i]] = i
        rlt = []
        start = 0
        temp_max = -1
        for i in range(len(S)):
            temp_max = max(temp_max, index[S[i]])
            if i == temp_max:
                rlt.append(temp_max - start + 1)
                start = i + 1
        return rlt
                
                

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值