763. Partition Labels (题目链接)
Medium
A string S
of lowercase English 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 English letters ('a'
to'z'
) only.
思路:
这个题要进行字符串的分段,分段的标准是,这个段里面的字符串不会再出现在其他的字符串中。要求是尽可能的分成更多的串,最后的返回结果是这些串的长度组成的一个数组。
我们从第一个字母开始,统计每个字母出现最远位置的索引,因为一个字母可能出现多次,我们先遍历一遍整个S,找出这个字母出现位置最大的索引,然后放到一个dict里面。比如上面的例子, 我们计算出来的结果是下面这样的。
{'a': 8, 'b': 5, 'c': 7, 'd': 14, 'e': 15, 'f': 11, 'g': 13, 'h': 19, 'i': 22, 'j': 23, 'k': 20, 'l': 21}
我们接着再遍历一遍整个S,用一个变量存在当前经过的最大索引,一个变量记录当前段的开始索引,当当前字母的索引等于当前最大索引的时候,整个段结束,计算长度,存入结果数组里,然后将记录开始索引的变量置为下一个索引。
import collections
class Solution:
def partitionLabels(self, S: str) -> List[int]:
index = collections.defaultdict(int)
for i in range(len(S)):
index[S[i]] = i
rlt = []
start = 0
temp_max = -1
for i in range(len(S)):
temp_max = max(temp_max, index[S[i]])
if i == temp_max:
rlt.append(temp_max - start + 1)
start = i + 1
return rlt