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

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)

Last updated