下面是一个示例代码,可以实现打印字符串s中字母按字母顺序排列的最长子串的功能:
def longest_substring(s):
longest = ""
current = ""
for i in range(len(s)):
if current == "" or ord(s[i]) >= ord(current[-1]):
current += s[i]
else:
if len(current) > len(longest):
longest = current
current = s[i]
if len(current) > len(longest):
longest = current
return longest
s = input("请输入一个字符串:")
result = longest_substring(s)
print("最长子串为:", result)
运行示例:
请输入一个字符串:azcbobobegghakl
最长子串为: beggh
该代码通过遍历字符串s,使用两个变量longest
和current
来记录当前的最长子串和当前正在构建的子串。当遇到一个字母比当前子串最后一个字母小的字母时,就将当前子串与最长子串进行比较,如果当前子串更长,则更新最长子串。最后返回最长子串。