-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpartition_labels.py
56 lines (41 loc) · 1.42 KB
/
partition_labels.py
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
56
from collections import defaultdict
def partitionLabels(s: str) -> list[int]:
letter_range = defaultdict(dict)
for i, n in enumerate(s):
if letter_range[n].get("last"):
letter_range[n]["last"] = i
else:
letter_range[n]["first"] = i
letter_range[n]["last"] = i
partition = []
last_index = letter_range[s[0]]["last"]
previous_partition = 0
for i, n in enumerate(letter_range):
if letter_range[n]["first"] > last_index:
p = last_index+1 - previous_partition if previous_partition else last_index + 1
partition.append(p)
previous_partition += p
last_index = letter_range[n]["last"]
if letter_range[n]["first"] < last_index and letter_range[n]["last"] > last_index:
last_index = letter_range[n]["last"]
partition.append(last_index+1 - previous_partition)
s = "abcdefghija"
partitionLabels(s)
def partitionLabels(s: str) -> list[int]:
letter_range = defaultdict()
for i, n in enumerate(s):
letter_range[n] = i
partition = []
i = 0
while i < len(s):
end = letter_range[s[i]]
j = i + 1
while (j != end):
if letter_range[s[j]] > end:
end = letter_range[s[j]]
j += 1
partition.append(j - i +1)
i = j + 1
print(partition)
s = "ababcbacadefegdehijhklij"
partitionLabels(s)