LintCode 1045: Partition Labels

  1. Partition Labels

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
Example 1:
Input: S = “ababcbacadefegdehijhklij”
Output: [9,7,8]

Explanation:
The partitions are "ababcbaca", "defegde", "hijhklij".
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.

Example 2:
Input: S = “abcab”
Output: [5]

Explanation:
We can not split it. 

Notice
1.S will have length in range [1, 500].
2.S will consist of lowercase letters (‘a’ to ‘z’) only.

解法1:
我的思路跟网上的标准答案差不多。首先是找出每个字符的最后出现的位置,然后从头开始扫描,每次把posEnd更新到posEnd和当前字符最后出现的位置的最大值。如果p1==posEnd,说明当前这段已经没有新的字符出现了,可以单独作为一段。

class Solution {
public:
    /**
     * @param S: a string
     * @return: a list of integers representing the size of these parts
     */
    vector<int> partitionLabels(string &S) {
        int len = S.size();
        vector<int> lastPos(26, 0);
        
        int p1 = 0, p2 = 0;
        for (int i = 0; i < len; ++i) {
            lastPos[S[i] - 'a'] = i; 
        }

        vector<int> result;
        int posStart = 0, posEnd = 0;
        while(p1 < len && p2 < len) {
            p2 = lastPos[S[p1] - 'a'];
            posEnd = max(posEnd, p2);

            if (p1 == posEnd) {
                result.push_back(posEnd - posStart + 1);
                posStart = posEnd + 1;
            }
            p1++;
        }
        
        return result;
    } 
};

代码更新在
https://github.com/luqian2017/Algorithm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值