763. Partition Labels

A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and 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.

分割字符串,在保证每种字符只出现在一个子串的前提下,分段越多越好。

第一步是统计每种字符出现的区间,然后把重叠的区间合并就好了。最后返回每个区间的长度。

class Solution {
private:
    struct cmp {
        bool operator() (const vector<int> &a, const vector<int> &b) {
            return a[0] > b[0];
        }
    };
public:
    vector<int> partitionLabels(string S) {
        unordered_map<char, vector<int>> m;
        for (int i=0; i<S.length(); ++i) {
            if (m[S[i]].empty())
                m[S[i]] = {i, i};
            else
                m[S[i]][1] = i;
        }
        
        priority_queue<vector<int>, vector<vector<int>>, cmp> pq;
        for (auto it=m.begin(); it!=m.end(); ++it)  pq.push(it->second);
        
        vector<vector<int>> par;
        par.push_back({pq.top().front(), pq.top().back()});
        pq.pop();
        while (pq.size()) {
            int low = pq.top().front();
            int high = pq.top().back();
            if (low<par.back().back())
                par.back().back() = max(par.back().back(), high);
            else
                par.push_back({low, high});
            pq.pop();
        }
        
        vector<int> res;
        for (auto v: par)
            res.push_back(v.back()-v.front()+1);
        return res;
    }
};

 

posted @ 2018-01-15 15:01  Zzz...y  阅读(384)  评论(0编辑  收藏  举报