程序查找列表每个分区的大小,每个字母在Python中最多显示一个
假设我们有一个小写的字符串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]
热门推荐
10 写老师离别祝福语简短
11 朋友生闺女简短祝福语
12 生日祝福语对妈妈简短
13 奶茶便利贴祝福语简短
14 老人去世简短祝福语
15 对公司年会祝福语简短
16 官宣祝福语简短霸气
17 幼师离别祝福语老师简短
18 简短元旦祝福语古言