forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPartitionLabels.java
More file actions
32 lines (25 loc) · 771 Bytes
/
PartitionLabels.java
File metadata and controls
32 lines (25 loc) · 771 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Time complexity is O(n)
// Space complexity is O(1)
class PartitionLabels {
public List<Integer> partitionLabels(String S) {
int[] indexLast = new int[26];
// abca
for(int i=0;i<S.length();i++){
char c = S.charAt(i);
int index = c -'a';
indexLast[index] = i;
}
List<Integer> ans = new ArrayList<>();
int lastIndex = -1;
int start = 0;
for(int i=0;i<S.length();i++){
int currLastIndex = indexLast[S.charAt(i) - 'a'];
lastIndex = Math.max(lastIndex, currLastIndex);
if(lastIndex == i){
ans.add(lastIndex +1 - start);
start = lastIndex +1;
}
}
return ans;
}
}