题目

A string S of lowercase English 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:

  1. Input: S = "ababcbacadefegdehijhklij"
  2. Output: [9,7,8]
  3. Explanation:
  4. The partition is "ababcbaca", "defegde", "hijhklij".
  5. This is a partition so that each letter appears in at most one part.
  6. 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 English letters ('a' to 'z') only.

题意

将给定字符串划分成尽可能多的子串,使得同一个字母只出现在一个子串中。

思路

主要思想是记录每个字母出现的最后一个位置,得到每个字母的出现区间。对于一个字母的出现区间S,如果其中有字母的结束位置大于S的右端点,那么需要更新右端点,直到右端点对应字母的结束位置就是右端点本身,这样就找到了一个符合条件的子串。


代码实现

Java

  1. class Solution {
  2. public List<Integer> partitionLabels(String S) {
  3. List<Integer> ans = new ArrayList<>();
  4. int[] ends = new int[26];
  5. for (int i = 0; i < S.length(); i++) {
  6. char c = S.charAt(i);
  7. ends[c - 'a'] = Math.max(ends[c - 'a'], i);
  8. }
  9. int start = 0, end = 0;
  10. for (int i = 0; i < S.length(); i++) {
  11. char c = S.charAt(i);
  12. end = Math.max(end, ends[c - 'a']);
  13. if (end == i) {
  14. ans.add(end - start + 1);
  15. start = i + 1;
  16. }
  17. }
  18. return ans;
  19. }
  20. }