forked from tangweikun/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
36 lines (31 loc) · 843 Bytes
/
index.ts
File metadata and controls
36 lines (31 loc) · 843 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
33
34
35
36
export const partitionLabels = (S: string) => {
let alphabet = Array.from({ length: 26 }, _ => ({
min: Infinity,
max: -Infinity,
}))
for (let i = 0; i < S.length; i++) {
alphabet[S.charCodeAt(i) - 97].min = Math.min(
alphabet[S.charCodeAt(i) - 97].min,
i,
)
alphabet[S.charCodeAt(i) - 97].max = Math.max(
alphabet[S.charCodeAt(i) - 97].max,
i,
)
}
const filteredAlphabet = alphabet
.filter(({ min, max }) => min <= max)
.sort((x, y) => x.min - y.min)
let temp: any = {}
let res = []
for (let set of filteredAlphabet) {
if (temp.min !== undefined && set.min <= temp.max) {
temp.max = Math.max(temp.max, set.max)
res[res.length - 1] = temp.max - temp.min + 1
} else {
temp = set
res.push(set.max - set.min + 1)
}
}
return res
}