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

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.

题目给定一串字符串,将字符串切割成子字符串,使得每个字符最多只能出现在一个子字符串中,并且尽可能多的切割子字符串。问每个子字符串的大小是多少。

思路:用一个数组end记录每个字符最后出现的位置,依次遍历字符串,每遍历过一个字符更新当前子字符串(起始位置start)的最后一个字符位置last,当当前字符即为最后一个字符时,可以切割,更新结果。代码如下:

class Solution {
public:
    vector<int> partitionLabels(string s) {
        vector<int> end(26, -1);
        int count = 0;
        for(int i=s.length()-1; i>=0; i--){
            if(end[s[i]-'a'] == -1) {
                end[s[i]-'a'] = i;
                count++;
            }
            if(count == 26) break;
        }
        vector<int> res;
        int start = 0, last = end[s[0] - 'a'];
        for(int i = 0; i < s.length(); i++){
            last = max(last, end[s[i]-'a']);
            if(last == i){
                res.push_back(last - start + 1);
                start = i + 1;
            }
        }
        return res;
    }
};

time: O(N)

space: O(1) (不算结果的话)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值