程序查找列表每个分区的大小,每个字母在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 爸妈简短婚礼祝福语大全