on
LeetCode Problem: 763. Partition Labels
Problem description can be found here.
What we need to do:
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.
Here is a solution in Scala:
Given a string lastChar
method returns a map, where key is the character and its value is index of last occurrence of that character in the string S
.
For string :"ababcbacadefegdehijhklij"
lastChar
method will return this map :
Now we traverse over the string and checks last occurrence of that char using the map we got from lastChar
, and we store last index in j
. Whenever current index and j is equal, we can say that partition is possible at index i
. So we store the number of character in the List res
and move to the next index. when we reach the last index we simply returns the List res
.