763. Partition Labels

Difficulty:
Related Topics:
Similar Questions:

Problem

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:

Solution (Java)

class Solution {
    public List<Integer> partitionLabels(String s) {
        char[] letters = s.toCharArray();
        List<Integer> result = new ArrayList<>();
        int[] position = new int[26];
        for (int i = 0; i < letters.length; i++) {
            position[letters[i] - 'a'] = i;
        }
        int i = 0;
        int prev = -1;
        int max = 0;
        while (i < letters.length) {
            if (position[letters[i] - 'a'] > max) {
                max = position[letters[i] - 'a'];
            }
            if (i == max) {
                result.add(i - prev);
                prev = i;
            }
            i++;
        }
        return result;
    }
}

Solution (Javascript)

/**
 * @param {string} s
 * @return {number[]}
 */
var partitionLabels = function(s) {
  let lastIndex = {}
  for (let i = 0; i < s.length; i++){
    lastIndex[s[i]]= i
  }
  let partitions = []
  let start = 0
  let end = 0
  for (let i = 0; i < s.length; i++) {
    end = Math.max(end, lastIndex[s[i]])
    if (i === end) {
      partitions.push(i - start + 1)
      start = i + 1
    }
  }
  return partitions
};

Explain:

nope.

Complexity: