-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPartitionLabels.java
More file actions
55 lines (47 loc) · 1.65 KB
/
PartitionLabels.java
File metadata and controls
55 lines (47 loc) · 1.65 KB
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
package leetcode;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* PartitionLabels
* https://leetcode-cn.com/problems/partition-labels/
*
* @since 2020-10-22
*/
public class PartitionLabels {
public static void main(String[] args) {
PartitionLabels sol = new PartitionLabels();
List<Integer> res = sol.partitionLabels("ababcbacadefegdehijhklij");
for (Integer length : res) {
System.out.println(length);
}
}
public List<Integer> partitionLabels(String S) {
// store each char's last index
Map<Character, Integer> charEndIdx = new HashMap<>();
for (int i = 0; i < S.length(); i++) {
charEndIdx.put(S.charAt(i), i);
}
List<Integer> subStrLength = new LinkedList<>();
// try to spilt from first char to end char
for (int startIdx = 0; startIdx < S.length(); ) {
// start: detect substring
// firstly, the start char decide the end char
int endIdx = charEndIdx.get(S.charAt(startIdx));
for (int i = startIdx; i <= endIdx; i++) {
// recursively, the inner char affect the substring end index (or length)
int currEndIdx = charEndIdx.get(S.charAt(i));
if (currEndIdx > endIdx) {
endIdx = currEndIdx;
}
}
// end: detect substring
// store current substring length
subStrLength.add(endIdx - startIdx + 1);
// for next substring
startIdx = endIdx + 1;
}
return subStrLength;
}
}