leetcode

763.划分字母区间

力扣链接

class Solution{
public:
    std::vector<int> partitionLabels(std::string s) {
        std::vector<int> res;
        int hash[26] = {0};
        // 保存每个字母的最大索引
        for (int i = 0; i < s.size(); i++) hash[s[i]-'a'] = i;
    
        int left = 0, right = 0;
        for (int i = 0; i < s.size(); i++){
            right = std::max(right, hash[s[i] - 'a']);
            // 比较每个字母最远的重复字母索引作为right 遍历到最远的索引
            if (i == right){
                res.push_back(right - left + 1);
                left = right + 1;
            }
        }
        return res;
    }    
};