763 Partition Labels

1. Question

A stringSof 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. Swill have length in range[1, 500].

  2. Swill consist of lowercase letters ('a'to'z') only.

2. Implementation

(1) Two Pointers

思路: 这题要求我们将一个label尽可能的分成多份,使得每一份里的字母不会再其他parition里出现。所以我们用map数组记录每个字母在S中最后出现的index,然后用两个指针last, start去记录每一个partition的结尾和开头。

3. Time & Space Complexity

Two Pointers: 时间复杂度O(n), 空间复杂度O(n)

Last updated

Was this helpful?