编写一个程序,打印 s 中字母按字母顺序出现的最长子串

Write a program that prints the longest substring of s in which the letters occur in alphabetical order

代码运行良好,输出似乎正常。但是我的print在for循环里面,这让我怀疑编码是否正确:

s = 'azcbobobegghakl'
i = 0
increase = 0
longest = 1
for i in range(len(s) - 1):
        if s[i+1] >= s[i]:
           increase +=1
        else:
            if increase > longest:
               longest = increase
               print ("
Longest substring in alphabetical order is:"+""+s[i-longest:i+1])

            increase =0

你的疑惑是对的。如果你的字符串包含一些合适的子串,并且长度越来越长,你将把它们全部输出

不要立即打印,只需记住索引 i 和长度 longest(或子字符串边界),并在循环后输出最佳字符串。

if increase > longest:
           longest = increase
           beststart = i-longest
           bestend = i+1
           increase = 0
#With the help of MIT pythontutor(www.pythontutor.com) and
their exercise code test machine,I reworte my code and achieve its function in any string.


i = 0
increase = 0
longest = 0
tem_longest= 0
max_i = 0
start = 0
end = 0 
for i in range(len(s)-1 ):
        if s[i+1] >= s[i]:
           increase +=1
           tem_longest = increase
           max_i=i+1
           if increase==(len(s)-1):
              longest = increase 
              max_i=i+1
              start = max_i-longest
              end = max_i+1
              break  
        else:
            max_i=i
            tem_longest = increase
            increase =0

        if tem_longest > longest:
           longest = tem_longest
           start = max_i-longest
           end = max_i+1

        if i+1 == (len(s)-1) and tem_longest == 0 and longest == 0:
           start = 0
           end = 1

print ("Longest substring in alphabetical order is:"+""+s[start:end])

我会这样写:

s = 'abcaakabcdeakk'
i = 0
increase = 0
longest = 1
longest_end = 1
for i in range(len(s)):
        if i < len(s)-1 and s[i+1] >= s[i]:
           increase += 1
        else:
            if increase > longest:
               longest = increase
               longest_end = i
            increase = 0
print ("Longest substring in alphabetical order is:" + s[longest_end-longest:longest_end+1])