-
Notifications
You must be signed in to change notification settings - Fork 277
/
PartitionLabels.java
55 lines (47 loc) · 1.36 KB
/
PartitionLabels.java
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Solution {
public List<Integer> partitionLabels(String s) {
List<Integer> ans = new ArrayList<>();
int[] endIndex = new int[26];
for(int i =0;i<s.length();i++){
endIndex[s.charAt(i) - 'a'] = i;
}
int i = 0; // start Pointer
while(i<s.length()){
char startChar = s.charAt(i);
int terminalIndex = endIndex[startChar-'a'];
for(int j= 0;j<=terminalIndex;j++){
terminalIndex = Math.max(terminalIndex, endIndex[s.charAt(j)-'a']);
}
ans.add(terminalIndex- i+1);
i=terminalIndex+1;
}
return ans;
}
}
// @saorav21994
// TC : O(n)
// SC : O(26) ~ constant
// Parse string and keep last position of each character. Re-parse string and if (last position of cur char == cur index), add this partition to list
class Solution {
public List<Integer> partitionLabels(String s) {
int l = s.length();
int hash [] = new int[26];
for (int i = 0; i < l; i++) {
char ch = s.charAt(i);
hash[ch-97] = i;
}
List<Integer> res = new ArrayList<>();
int target = -1;
int prev = 0;
for (int i = 0; i < l; i++) {
char ch = s.charAt(i);
target = Math.max(target, hash[ch-97]);
if (i == target) {
res.add(i+1-prev);
prev = i+1;
target = -1;
}
}
return res;
}
}