Skip to content

Latest commit

 

History

History

763

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.

Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.

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.

Example 2:

Input: s = "eccbbbbdec"
Output: [10]

 

Constraints:

  • 1 <= s.length <= 500
  • s consists of lowercase English letters.

Companies:
Amazon, Facebook, Google, Oracle

Related Topics:
Hash Table, Two Pointers, String, Greedy

Similar Questions:

Solution 1. Counting + Bitmask

For every character that appears in the current range, we must exhaust all its occurrences.

// OJ: https://leetcode.com/problems/partition-labels/
// Author: github.com/lzl124631x
// Time: O(S)
// Space: O(1)
class Solution {
public:
    vector<int> partitionLabels(string S) {
        int cnt[26] = {};
        for (char c : S) cnt[c - 'a']++;
        vector<int> ans;
        for (int i = 0, prev = 0; i < S.size();) {
            int mask = 0; // `mask` is a bitmask representing all the characters that we've seen in the current range and haven't exhausted all their occurrences.
            do {
                int key = S[i++] - 'a';
                cnt[key]--;
                mask |= 1 << key; 
                if (cnt[key] == 0) mask ^= 1 << key; // If we've exhausted this character, remove it from the mask
            } while (mask); // When `mask != 0`, there are still some characters that have remaining occurrences -- we keep looping
            ans.push_back(i - prev);
            prev = i;
        }
        return ans;
    }
};

Solution 2. Extending Boundary

// OJ: https://leetcode.com/problems/partition-labels/
// Author: github.com/lzl124631x
// Time: O(S)
// Space: O(1)
class Solution {
public:
    vector<int> partitionLabels(string s) {
        int N = s.size(), last[26] = {};
        memset(last, -1, sizeof(last));
        for (int i = 0; i < N; ++i) last[s[i] - 'a'] = i;
        vector<int> ans;
        for (int i = 0; i < N;) {
            int start = i;
            for (int end = i + 1; i < end; ++i) end = max(end, last[s[i] - 'a'] + 1);
            ans.push_back(i - start);
        }
        return ans;
    }
};