|
3 | 3 | import java.util.ArrayList;
|
4 | 4 | import java.util.List;
|
5 | 5 |
|
6 |
| -/** |
7 |
| - * 763. Partition Labels |
8 |
| - * |
9 |
| - * A string S of lowercase letters is given. |
10 |
| - * We want to partition this string into as many parts as possible so that each letter appears |
11 |
| - * in at most one part, and return a list of integers representing the size of these parts. |
12 |
| -
|
13 |
| - Example 1: |
14 |
| - Input: S = "ababcbacadefegdehijhklij" |
15 |
| - Output: [9,7,8] |
16 |
| - Explanation: |
17 |
| - The partition is "ababcbaca", "defegde", "hijhklij". |
18 |
| - This is a partition so that each letter appears in at most one part. |
19 |
| - A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts. |
20 |
| -
|
21 |
| - Note: |
22 |
| - S will have length in range [1, 500]. |
23 |
| - S will consist of lowercase letters ('a' to 'z') only. |
24 |
| - */ |
25 | 6 | public class _763 {
|
26 | 7 |
|
27 |
| - public static class Solution1 { |
28 |
| - public List<Integer> partitionLabels(String S) { |
29 |
| - List<Integer> result = new ArrayList<>(); |
30 |
| - int[] last = new int[26]; |
31 |
| - /**This is the key step: |
32 |
| - * we find the last occurrence of each letter and record them in last[]*/ |
33 |
| - for (int i = 0; i < S.length(); i++) { |
34 |
| - last[S.charAt(i) - 'a'] = i; |
35 |
| - } |
36 |
| - /**record the last end index of the current substring*/ |
37 |
| - int end = 0; |
38 |
| - int start = 0; |
39 |
| - for (int i = 0; i < S.length(); i++) { |
40 |
| - end = Math.max(end, last[S.charAt(i) - 'a']); |
41 |
| - if (end == i) { |
42 |
| - result.add(end - start + 1); |
43 |
| - start = end + 1; |
| 8 | + public static class Solution1 { |
| 9 | + public List<Integer> partitionLabels(String S) { |
| 10 | + List<Integer> result = new ArrayList<>(); |
| 11 | + int[] last = new int[26]; |
| 12 | + /**This is the key step: |
| 13 | + * we find the last occurrence of each letter and record them in last[]*/ |
| 14 | + for (int i = 0; i < S.length(); i++) { |
| 15 | + last[S.charAt(i) - 'a'] = i; |
| 16 | + } |
| 17 | + /**record the last end index of the current substring*/ |
| 18 | + int end = 0; |
| 19 | + int start = 0; |
| 20 | + for (int i = 0; i < S.length(); i++) { |
| 21 | + end = Math.max(end, last[S.charAt(i) - 'a']); |
| 22 | + if (end == i) { |
| 23 | + result.add(end - start + 1); |
| 24 | + start = end + 1; |
| 25 | + } |
| 26 | + } |
| 27 | + return result; |
44 | 28 | }
|
45 |
| - } |
46 |
| - return result; |
47 | 29 | }
|
48 |
| - } |
49 | 30 |
|
50 | 31 | }
|
0 commit comments