[leetcode-763] Partition Labels

本文介绍了一种高效的算法,用于将一个由小写英文字母组成的字符串分割成尽可能多的部分,使得每个字母只出现在一个部分中。通过查找每个字符的首次和最后一次出现的位置,该算法能够确定每个部分的边界,并返回表示各部分长度的整数列表。

Description

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

Solution

  1. Select a partition with the first and last occurrence of a letter, mark them as start and end of a list respectively.
  2. Iterate all letters within the list.
  3. If found letter have last occurrence bigger than end, update the end accordingly.
  4. If end was reached, update count with end-start+1
  5. Start new round with end + 1

code:

class Solution {
public:
    vector<int> partitionLabels(string S) {
        vector<int> result;
        int lastOccurence[26];
        
        for(int i = 0; i < S.length(); i++) {
            lastOccurence[S[i] - 'a'] = i;
        }
        
        int i = 0;
        while(i < S.length()) {
            int end = lastOccurence[S[i] - 'a'];
            
            int j = i;
            
            while(j<end) {
                end = max(end, lastOccurence[S[j] - 'a']);
                j++;
            }
            
            int count = j - i + 1;
            result.push_back(count);
            
            i = j + 1;
        }
        
        return result;
        
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值