You are given a string s
. We want to partition this string into as many parts as possible so that each letter appears in at most one part. Return a list of integers representing the size of these parts.
Input: s = "ababcbacadefegdehijhklij"
Output: [9, 7, 8]
Explanation:
The partitions are "ababcbaca", "defegde", "hijhklij".
This is because:
- "a", "b", and "c" appear in the first part.
- "d", "e", "f", and "g" appear in the second part.
- "h", "i", "j", "k", and "l" appear in the third part.
s
guaranteed to be non-empty?Assumptions based on standard problem constraints:
s
contains only lowercase English letters.s
is at most 500.n
is the length of the string s
. This is because:
def partition_labels(s):
# Calculate the last occurrence of each character
last_occurrence = {char: idx for idx, char in enumerate(s)}
partitions = []
start = 0
end = 0
# Traverse the string to find the partitions
for idx, char in enumerate(s):
end = max(end, last_occurrence[char])
# When we reach the end of the current partition
if idx == end:
partitions.append(end - start + 1)
start = idx + 1
return partitions
# Example usage:
s = "ababcbacadefegdehijhklij"
print(partition_labels(s)) # Output: [9, 7, 8]
This code snippet achieves the desired partitioning of the string as described in the problem statement, ensuring that each character appears in at most one part of the partitioned string.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?