#Leetcode# 763. Partition Labels

https://leetcode.com/problems/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.

 

Note:

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

代码:

class Solution {
public:
    vector<int> partitionLabels(string S) {
        vector<int> ans;
        int len = S.length();
        map<char, int> mp;
        for(int i = 0; i < len; i ++) 
            mp[S[i]] = i;
        int st = 0, maxx = 0;
        for(int i = 0; i < len; i ++) {
            maxx = max(maxx, mp[S[i]]);
            if(i == maxx) {
                ans.push_back(i - st + 1);
                st = i + 1;
            }
        }
        return ans;
    }
};

  

代码(JAVA):

class Solution {
    public List<Integer> partitionLabels(String S) {
        int n = S.length();
        List<Integer> ans = new ArrayList<Integer>();
        
        int st = 0, maxx = 0;
        for(int i = 0; i < n; i ++) {
            maxx = Math.max(maxx, S.lastIndexOf(S.charAt(i)));
            if(maxx == i) {
                int t = i - st + 1;
                ans.add(t);
                st = i + 1;
            }
        }
        return ans;
    }
}

  

posted @ 2019-05-11 14:56  丧心病狂工科女  阅读(142)  评论(0编辑  收藏  举报