Partition Labels
Medium
Share
A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
Example 1:
Input: S = “ababcbacadefegdehijhklij”
Output: [9,7,8]
Explanation:
The partition is “ababcbaca”, “defegde”, “hijhklij”.
This is a partition so that each letter appears in at most one part.
A partition like “ababcbacadefegde”, “hijhklij” is incorrect, because it splits S into less parts.
class Solution(object):
def partitionLabels(self, S):
"""
:type S: str
:rtype: List[int]
"""
res = []
charlis = []
charlis2 = dict()
i = 0
while(i<len(S)):
if S[i] not in charlis:
charlis2[S[i]] = [i,-1]
charlis.append(S[i])
i+=1
for item in charlis:
for i in range(len(S)-1,-1,-1):
if S[i] == item:
charlis2[item][1] = i
break
left = 0
right = charlis2[charlis[0]][1]
print(left,right)
for item in charlis[1:]:
if charlis2[item][0]<right and charlis2[item][1]>right:
right = charlis2[item][1]
elif charlis2[item][0]>right:
res.append(right-left+1)
left = charlis2[item][0]
right = charlis2[item][1]
res.append(right-left+1)
return res