LeetCode 763. 划分字母区间

1、一上来先遍历数组,找到每个字母最后出现的位置。
2、再次遍历数组,保持一个last,表示当前至少应该在哪里分割

class Solution {
public:
    vector<int> partitionLabels(string s) {
        //先遍历一遍数组,记录每一个字母最后出现的位置;
        int index[26] = { 0 };
        for (int i = 0; i < s.size(); i++) {
            index[s[i] - 'a'] = i;
        }
        vector<int> res;
        int number = 0;
        //记录分割当前最少应该截止到last下标出
        int last = 0;
        for (int i = 0; i < s.size(); i++) {
            last = last > index[s[i] - 'a'] ? last : index[s[i]-'a'];
            number++;
            if (last == i) {
                res.push_back(number);
                number = 0;
            }
        }
        return res;
    }
};

原文地址:http://www.cnblogs.com/poteitoutou/p/16877737.html

发表评论

您的电子邮箱地址不会被公开。