Partition Labels

LeetCode Q 763 - Partition Labels

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:

  • S will have length in range [1, 500].
  • S will consist of lowercase letters (‘a’ to ‘z’) only.

Solution

For each letter encountered, process the last occurrence of that letter, extending the current partition [start, j] appropriately.

Code:

public List<Integer> partitionLabels(String S) {

	List<Integer> res = new ArrayList<>();

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

	int[] count = new int[26];
	for (int i = 0; i < S.length(); i++)
		count[ch - 'a'] = i;

	int start = 0, end = 0;

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

		if (i == end) {
			res.add(end - start + 1);
			start = end + 1;
		}
	}

	return res;
}

   Reprint policy


《Partition Labels》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC