leetcode刷題.763. 劃分字母區間.每日打卡

paradox_1_0發表於2020-10-22

解法:貪心 + 雙指標

程式碼:

class Solution {
public:
    vector<int> partitionLabels(string S) {

        vector<int> out_;
        int last_[26] = { 0 };
        for(int i = 0; i < S.length(); i++)
            last_[S[i] - 'a'] = i;

        int start_ = 0, end_ = 0;
        for(int j = 0; j < S.length(); j++) {

            end_ = max(end_, last_[S[j] - 'a']);
            if(j == end_) {
                out_.push_back(end_ - start_ + 1);
                start_ = j + 1;
            }
        }
        return out_;
    }
};

 

相關文章