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

spa*_*ame 11 python

我在另一个主题上找到了这个代码,但它按连续字符排序子字符串,而不是按字母顺序排序.如何按字母顺序更正?打印出来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
Run Code Online (Sandbox Code Playgroud)

小智 15

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)
Run Code Online (Sandbox Code Playgroud)

  • 解释它的一些注释或变量的有意义的名称将有助于提高可读性 (3认同)

Tim*_*ers 5

尝试改变这个:

        if len(set(substr)) != (end - start): # found duplicates or EOS
            break
        if (ord(max(sorted(substr))) - ord(min(sorted(substr))) + 1) == len(substr):
Run Code Online (Sandbox Code Playgroud)

对此:

        if len(substr) != (end - start): # found duplicates or EOS
            break
        if sorted(substr) == list(substr):
Run Code Online (Sandbox Code Playgroud)

这将显示ccl您的示例输入字符串.代码更简单,因为你试图解决一个更简单的问题:-)