Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1855074

Browse files
authored
Create Partition_Labels.py
1 parent bbead9b commit 1855074

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Time: O(N) and Space: O(N)
2+
3+
class Solution:
4+
def partitionLabels(self, s: str) -> List[int]:
5+
d = {}
6+
# Store the first and last index of each character.
7+
for i,v in enumerate(s):
8+
if v not in d:
9+
d[v] = [i,i]
10+
else:
11+
d[v][1] = i
12+
13+
14+
15+
# Now the problem is same as merge intervals.
16+
temp = list(d.values())
17+
st = [temp[0]]
18+
for item in temp[1:]:
19+
top = st[-1]
20+
if item[0] <= top[1]:
21+
top[1] = max(top[1], item[1])
22+
23+
else:
24+
st.append(item)
25+
26+
# Calculating the answer
27+
ans = [x[1]-x[0]+1 for x in st]
28+
return ans

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /