leetcode 763. Partition Labels 的思路与python实现

A string S of lowercase 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:

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

思路

一开始的思路是遍历,把每一个字母出现的第一个和最后一个作为区间,记录下来。然后再排序合并这些区间。

然后不小心看了官方的solution,看到了更优雅的做法。

一个字典记录每个字母最后出现的位置。

遍历字符串。

一个值记录遍历到的这些字符串所遇到的最后的位置。

如果这个值就是当前位置就说明可以切割了,记住这个位置。

注意一点,要求的返回值是每一块的长度,而不是index,所以还要记录上一次切割的位置用来减掉。

代码

官方的代码也很优雅。学到了一个enumerate函数,可以在遍历的时候获得index.

class Solution(object):
    def partitionLabels(self, S):
        last = {c: i for i, c in enumerate(S)} # 这一行很神奇
        j = anchor = 0
        ans = []
        for i, c in enumerate(S):
            j = max(j, last[c])
            if i == j:
                ans.append(i - anchor + 1)
                anchor = i + 1
            
        return ans

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值