763. Partition Labels

给定一个字符串,目标是将其划分为尽可能多的部分,确保每个字母只出现在一个部分中。返回一个整数列表,表示这些部分的长度。示例和约束情况详细说明了解题思路,使用哈希表记录每个字母的最后出现位置,时间复杂度和空间复杂度均为O(n)。
摘要由CSDN通过智能技术生成

You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.

Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.

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.

Example 2:

Input: s = "eccbbbbdec"
Output: [10]

Constraints:

  • 1 <= s.length <= 500
  • s consists of lowercase English letters.

To find a substring that satisfies the description, we need to find the substring that, for each letter in the string, the last position of those letters should be smaller or equal to i. We can use hashmap to store each letter's last position.  Time/ space complexity is both O(n)

Pay attention: the way to initialize the hashmap

class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        last = {c:i for i,c in enumerate(s)}
        start = 0 
        end = 0
        res = []
        for i in range(len(s)):
            end = max(end, last[s[i]])
            if i == end:
                res.append(end-start+1)
                start = i + 1
        return res

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值