程序查找列表每个分区的大小,每个字母在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 教师闺蜜祝福语简短