本文介绍了最长子字符串按字母顺序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写打印字母以字母顺序出现的s的最长子字符串的程序。例如,如果s ='azcbobobegghakl',则您的程序应打印

Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print

按字母顺序的最长子字符串是:beggh

Longest substring in alphabetical order is: beggh

在tie的情况下,打印第一个子字符串。例如,如果s ='abcbcd',则您的程序应打印

In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print

按字母顺序的最长子字符串是:abc

Longest substring in alphabetical order is: abc

推荐答案

在这里,我已经帮助edx学生完成了代码:

Here you go edx student i've been helped to finish the code :

from itertools import count

def long_sub(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(substr) != (end - start): # found duplicates or EOS
                break
            if sorted(substr) == list(substr):
                maxsubstr = substr
    return maxsubstr

sub = (long_sub(s))
print "Longest substring in alphabetical order is: %s" %sub

这篇关于最长子字符串按字母顺序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:33