[leetcode] 763. Partition Labels

Description

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.

分析

题目的意思是:给定一个字符串,要求分几个子串,每个字串中每个字符至多出现一个子串中。

  • 用hash表建立字母和其最后出现位置之间的映射,那么对于题目中的例子来说,我们可以得到如下映射:
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了,我们维护一个start变量,是当前子串的起始位置,还有一个last变量,是当前子串的结束位置,每当我们遍历到一个字母,我们需要在HashMap中提取出其最后一个位置,因为一旦当前子串包含了一个字母,其必须包含所有的相同字母,所以我们要不停的用当前字母的最后一个位置来更新last变量,只有当i和last相同了,即当i = 8时,当前子串包含了所有已出现过的字母的最后一个位置,即之后的字符串里不会有之前出现过的字母了,此时就应该是断开的位置,我们将长度9加入结果res中,同理类推,我们可以找出之后的断开的位置,

代码

class Solution {
public:
    vector<int> partitionLabels(string S) {
        vector<int> res;
        int n=S.size();
        int start=0;
        int last=0;
        unordered_map<char,int> m;
        for(int i=0;i<n;i++){
            m[S[i]]=i;
        }
        for(int i=0;i<n;i++){
            last=max(last,m[S[i]]);
            if(i==last){
                res.push_back(i-start+1);
                start=i+1;
            }
        }
        return res;
    }
};

Python

下面是python的实现,核心思想就是使用map记录每个字符最后出现的位置,接下来遍历的时候,看是否遍历到字符最后出现的位置,然后根据这个标志来判定是否是符合要求的字串(字符只包含在一个字串中)。

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

参考文献

[LeetCode] Partition Labels 分割标签

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值