假设我们有一个小写的字符串s,我们可以将s分成尽可能多的段,以便每个字母最多出现一个,并以列表的形式找到分区的大小。
因此,如果输入类似于s =“ momoplaykae”,则输出将为[4,1,1,4,4,1],因为字符串被拆分为[“ momo”,“ p”,“ l”,“ ayka”,“ e”]。
让我们看下面的实现以更好地理解-
from collections import Counter class Solution: def solve(self, s): count = Counter(s) out = [] stk = [] length = 0 for char in s: count[char] -= 1 length += 1 while count[char] != 0 or stk: if count[char] != 0: stk.append(char) break if stk and count[stk[-1]] == 0: stk.pop() else: break if not stk and count[char] == 0: out += [length] length = 0 return out ob = Solution() s = "momoplaykae" print(ob.solve(s))
"momoplaykae"输出结果
[4, 1, 1, 4, 1]