LeetCode763. Partition Labels

该篇文章介绍了一个编程问题,给定一个字符串,要求将其分割成尽可能多的部分,使得每个字符出现在每个部分中至多一次。提供了一种解决方案,利用哈希映射记录每个字符最后出现的位置,找到最大位置作为分界点,输出各部分的大小。
摘要由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.

二、题解

class Solution {
public:
    vector<int> partitionLabels(string s) {
        int n = s.size();
        vector<int> map(26,0);
        //记录字符出现的最远位置的下标
        for(int i = 0;i < n;i++){
            map[s[i]-'a'] = i;
        }
        vector<int> res;
        int left = 0,right = 0;
        for(int i = 0;i < n;i++){
            right = max(map[s[i]-'a'],right);
            if(i == right){
                res.push_back(right-left+1);
                left = i + 1;
            }
        }
        return res;
    }
};
  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值