这个怎么样:
def longest_ascending(s): matches = [] current = [s[0]] for index, character in enumerate(s[1:]): if character >= s[index]: current.append(character) else: matches.append(current) current = [character] matches.append(current) return "".join(max(matches, key=len))
说明:
matches
是所有带有“升序”字符的子字符串的列表。current
是当我们遍历字符串时所构建的升序字符的子字符串。我们从字符串的第一个字符开始。- 现在,我们逐字符遍历剩余的字符串。
enumerate()
帮助我们跟踪 前一个 字符的索引(因为枚举始于0
并且我们从第二个字符开始迭代该字符串)。 - 如果当前字符“大于或等于”前一个字符,则将其添加到当前子字符串中并继续。
- 如果不是,我们将当前子字符串添加到子字符串列表中,并使用当前字符播种下一个子字符串。
- 迭代结束后,不要忘记将当前子字符串也添加到列表中。



