【Leetcode-763】Partition Labels 题解

题目

https://leetcode.com/problems/partition-labels/

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.
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.

分析

同一个字母不能在一个分区中出现两次,那么只考虑最先和最后的这个字母。每一对字母表示了字符串中的一个连续区域。每个区域分三种情况:

  1. 完全被某一其他区域包围 如 abba:这种情况下被包围的区就可以不考虑了
  2. 和其他区域相交 ,如abcabc 三个区域相互嵌套:有重叠的区域联合成一个更大的区域,合成区域也符合三种情况的判定标准
  3. 不被任一区域包围,且不相交:这是一个完整的分区

我们只需要确定所有的第三种区域即可。

算法流程

  1. 遍历一遍,找到所有字母最左边和最右边出现的下标,为初始分区
  2. 将初始分区按照左下标排序
  3. 将“合并分区”初始化为排序第一个分区
  4. 遍历所有初始分区:
    (a) 如果下一个分区的左下标大于当前合并分区的右下标,那么当前“合并分区”结算,并更新为新分区的左右下标
    (b) 否则,如果下一个分区的右下标,大于当前合并分区的右下标,则更新当前“合并分区”的右下标,相当于扩展“合并分区”

代码

class Solution {
public:
    vector<int> partitionLabels(string s) {
        vector<int> result;
        int left[128],right[128];        
        bool appeared[128]={false};
        int len = s.size();
        for (int i=0;i<len;i++){
            if (!appeared[s[i]])
            {
                appeared[s[i]] = true;
                left[s[i]] = i;
            }                        
            right[s[i]] = i;
        }
        class Partition{
            public:
            int l,r;
            Partition(int l_,int r_){
                l = l_;
                r = r_;
            }
            bool operator<(const Partition & x) const{
                return l<x.l;
            }
        };
        vector<Partition> p;        
        for (char i='a';i<='z';i++)
            if (appeared[i])
                p.push_back(Partition(left[i],right[i]));

        sort(p.begin(),p.end());
        
        int l=-1,r;
        for (vector<Partition>::iterator iter = p.begin();iter!=p.end();iter++){
            if (l==-1){
                l = iter->l;
                r = iter->r;
            }
            else
            if (iter->l>r){
                result.push_back(r-l+1);
                l = iter->l;
                r = iter->r;
            }
            else if (iter->r>r)
                r = iter->r;
        }
        result.push_back(r-l+1);
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值