gpt4 book ai didi

python - 按字母顺序查找最长的子串

转载 作者:太空狗 更新时间:2023-10-29 17:55:04 25 4
gpt4 key购买 nike

我有在另一个主题上找到的这段代码,但它按连续字符而不是按字母顺序对子字符串进行排序。如何按字母顺序更正它?它打印出 lk,我想打印 ccl。谢谢

ps:我是python初学者

s = 'cyqfjhcclkbxpbojgkar'
from itertools import count

def long_alphabet(input_string):
maxsubstr = input_string[0:0] # empty slice (to accept subclasses of str)
for start in range(len(input_string)): # O(n)
for end in count(start + len(maxsubstr) + 1): # O(m)
substr = input_string[start:end] # O(m)
if len(set(substr)) != (end - start): # found duplicates or EOS
break
if (ord(max(sorted(substr))) - ord(min(sorted(substr))) + 1) == len(substr):
maxsubstr = substr
return maxsubstr

bla = (long_alphabet(s))
print "Longest substring in alphabetical order is: %s" %bla

最佳答案

s = 'cyqfjhcclkbxpbojgkar'
r = ''
c = ''
for char in s:
if (c == ''):
c = char
elif (c[-1] <= char):
c += char
elif (c[-1] > char):
if (len(r) < len(c)):
r = c
c = char
else:
c = char
if (len(c) > len(r)):
r = c
print(r)

关于python - 按字母顺序查找最长的子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19601903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com