leetcode763 - Partition Labels - medium

A string S of lowercase English 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.

 

Note:

  • S will have length in range [1, 500].
  • S will consist of lowercase English letters ('a' to 'z') only.

 

断开的点都是某个字母最后出现的地方。先用hashmap统计一下每个char最后出现的位置,再从头扫一遍,start和end标记当前partition的头尾,end每次更新成到目前出现的所有char的最后出现位置,如果i和这个最尾值相同了就表示i之前的所有字母到此都结束了,断开。
 
实现:
class Solution {
public:
    vector<int> partitionLabels(string S) {
        
        vector<int> res;
        
        unordered_map<char, int> m; //last index of a char
        for (int i=0; i<S.size(); i++)
            m[S[i]] = i;
        
        int start = 0, last = 0;
        for (int i=0; i<S.size(); i++){
            last = max(last, m[S[i]]);
            if (last == i){
                res.push_back(last-start+1);
                start = i+1;
            }
        }
        
        return res;       
        
    }
};

 

posted @ 2020-08-24 08:54  little_veggie  阅读(163)  评论(0)    收藏  举报