1
+ class Solution {
2
+ // O(n)
3
+ public List <Integer > partitionLabels (String S ) {
4
+ // record the last index of each character
5
+ // sweep and record when i == end(max end of current interval)
6
+ if (S == null || S .length () == 0 ) return new ArrayList <>();
7
+
8
+ int [] map = new int [26 ];
9
+ for (int i = 0 ; i < S .length (); i ++) {
10
+ map [S .charAt (i ) - 'a' ] = i ;
11
+ }
12
+ int start = 0 , end = 0 ;
13
+ List <Integer > res = new ArrayList <>();
14
+ for (int i = 0 ; i < S .length (); i ++) {
15
+ end = Math .max (end , map [S .charAt (i ) - 'a' ]);
16
+ if (i == end ) {
17
+ res .add (end - start + 1 );
18
+ start = end + 1 ;
19
+ }
20
+ }
21
+ return res ;
22
+ }
23
+
24
+
25
+ // // O(nlogn)
26
+ // public List<Integer> partitionLabels(String S) {
27
+ // Map<Character, int[]> map = new HashMap<>();
28
+ // for(int i = 0; i < S.length(); i++) {
29
+ // char c = S.charAt(i);
30
+ // int[] expand = new int[] {i, i};
31
+ // if(map.containsKey(c)) {
32
+ // expand = map.get(c);
33
+ // expand[1] = i;
34
+ // }
35
+ // map.put(c, expand);
36
+ // }
37
+
38
+ // List<int[]> intervals = new ArrayList<>(map.values());
39
+ // intervals.sort(new Comparator<int[]>() {
40
+ // @Override
41
+ // public int compare(int[] i1, int[] i2) {
42
+ // return i1[0] == i2[0]? i1[1] - i2[1] : i1[0] - i2[0];
43
+ // }
44
+ // });
45
+
46
+ // List<Integer> res = new ArrayList<>();
47
+ // if(intervals.isEmpty()) return res;
48
+ // int start = -1, end = -1;
49
+ // for(int[] interval: intervals) {
50
+ // if(end == -1) {
51
+ // start = interval[0];
52
+ // end = interval[1];
53
+ // }
54
+ // else if(end >= interval[0]) {
55
+ // start = Math.min(start, interval[0]);
56
+ // end = Math.max(end, interval[1]);
57
+ // }
58
+ // else {
59
+ // res.add(end - start + 1);
60
+ // start = interval[0];
61
+ // end = interval[1];
62
+ // }
63
+ // }
64
+ // res.add(end - start + 1);
65
+ // return res;
66
+ // }
67
+ }
0 commit comments