> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/oj-practices/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/oj-practices/chapter1/two-pointers/763-partition-labels.md).

# 763     Partition Labels

## 763. [Partition Labels](https://leetcode.com/problems/partition-labels/description/)

## 1. Question

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.

## 2. Implementation

**(1) Two Pointers**

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

```java
class Solution {
    public List<Integer> partitionLabels(String S) {
        List<Integer> res = new ArrayList<>();

        if (S == null || S.length() == 0) {
            return res;
        }

        // map记录s中的character最后出现的index        
        int[] map = new int[26];
        for (int i = 0; i < S.length(); i++) {
            map[S.charAt(i) - 'a'] = i;
        }

        int last = 0, start = 0;

        for (int i = 0; i < S.length(); i++) {
            last = Math.max(last, map[S.charAt(i) - 'a']);

            // 找到分割点
            if (last == i) {
                res.add(last - start + 1);
                start = i + 1;
            }
        }
        return res;
    }
}
```

## 3. Time & Space Complexity

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