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.
Note:
S
will have length in range[1, 500]
.S
will consist of lowercase letters ('a'
to'z'
) only.
思路
一开始的思路是遍历,把每一个字母出现的第一个和最后一个作为区间,记录下来。然后再排序合并这些区间。
然后不小心看了官方的solution,看到了更优雅的做法。
一个字典记录每个字母最后出现的位置。
遍历字符串。
一个值记录遍历到的这些字符串所遇到的最后的位置。
如果这个值就是当前位置就说明可以切割了,记住这个位置。
注意一点,要求的返回值是每一块的长度,而不是index,所以还要记录上一次切割的位置用来减掉。
代码
官方的代码也很优雅。学到了一个enumerate函数,可以在遍历的时候获得index.
class Solution(object):
def partitionLabels(self, S):
last = {c: i for i, c in enumerate(S)} # 这一行很神奇
j = anchor = 0
ans = []
for i, c in enumerate(S):
j = max(j, last[c])
if i == j:
ans.append(i - anchor + 1)
anchor = i + 1
return ans