763. 划分字母区间

发布时间 2023-05-09 21:02:31作者: xiazichengxi

给你一个字符串 s 。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。

注意,划分结果需要满足:将所有划分结果按顺序连接,得到的字符串仍然是 s 。

返回一个表示每个字符串片段的长度的列表。


输入:s = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca"、"defegde"、"hijhklij" 。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 这样的划分是错误的,因为划分的片段数较少。

标准解法


class Solution {
public:
    vector<int> partitionLabels(string s) {
        int len = s.size();
        if(len == 1) return {1};
        int hash[27] = {0};
        for(int i = 0; i < len; i++){
            hash[s[i]-'a'] = i;
        }
        vector<int> res;
        res.clear();
        int start = 0;
        int M = hash[s[0] - 'a'];
        for(int i = 0; i < len; i++){
            if(M < hash[s[i] - 'a']){
                M = hash[s[i] - 'a'];
            }
            if(i == M){
                res.emplace_back(i - start + 1);
                start = i+1;
            }
        }
        return res;
    }
};