Skip to content

Commit 81dacd8

Browse files
committed
Runtime 35 ms (Top 90.78%) | Memory 13.0 MB (Top 54.16%)
1 parent 2f1c74f commit 81dacd8

File tree

1 file changed

+22
-20
lines changed

1 file changed

+22
-20
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,23 @@
1-
class Solution(object):
2-
def partitionLabels(self, s):
3-
"""
4-
:type s: str
5-
:rtype: List[int]
6-
"""
7-
m = map(s.index, s) # s: 'ababc' -> m: [0, 1, 0, 1, 4]
8-
n = len(s)
9-
res = []
1+
class Solution:
2+
def partitionLabels(self, s: str) -> List[int]:
3+
d = defaultdict(list)
4+
for i, char in enumerate(s):
5+
d[char].append(i)
6+
nums = []
107

11-
start = 0
12-
i = 0
13-
while i < n:
14-
for j in range(i+1, n):
15-
if m[j] <= i:
16-
i = j
17-
i += 1
18-
res.append(i - start)
19-
start = i
20-
21-
return res
8+
for v in d.values():
9+
nums.append([v[0], v[-1]])
10+
11+
start = nums[0][0]
12+
maxIndex = nums[0][1]
13+
ans = []
14+
for i in range(1, len(nums)):
15+
if nums[i][0] <= maxIndex:
16+
maxIndex = max(maxIndex, nums[i][1])
17+
else:
18+
ans.append(maxIndex - start + 1)
19+
start = nums[i][0]
20+
maxIndex = nums[i][1]
21+
ans.append(maxIndex - start + 1)
22+
# print(ans)
23+
return ans

0 commit comments

Comments
 (0)