Skip to content

Commit d0f120a

Browse files
committed
Time: 7 ms (38.93%), Space: 18 MB (13.36%) - LeetHub
1 parent da586b8 commit d0f120a

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

0768-partition-labels/0768-partition-labels.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# time complexity: O(n)
2-
# space complexity: O(1)
2+
# space complexity: O(k)
33
from typing import List
44

55

@@ -16,6 +16,30 @@ def partitionLabels(self, s: str) -> List[int]:
1616
left = right + 1
1717
return result
1818

19+
# time complexity: O(n)
20+
# space complexity: O(k)
21+
class Solution:
22+
def partitionLabels(self, s: str) -> List[int]:
23+
result = []
24+
lastIdx = [0] * 26
25+
firstIdx = [-1] * 26
26+
left, right = 0, 0
27+
for i, char in enumerate(s):
28+
lastIdx[ord(char) - ord("a")] = i
29+
for i, char in enumerate(s):
30+
index = ord(char) - ord("a")
31+
if firstIdx[index] == -1:
32+
firstIdx[index] = i
33+
if right < firstIdx[index]:
34+
result.append(right - left + 1)
35+
left = i
36+
right = i
37+
right = max(right, lastIdx[index])
38+
if right - left + 1 > 0:
39+
result.append(right - left + 1)
40+
41+
return result
42+
1943

2044
'''
2145
ababcbacadefegdehijhklij

0 commit comments

Comments
 (0)