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

时间:2017-07-03 14:19:48

标签: algorithm substring alphabetical

代码运行正常,输出似乎没问题。但我的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

3 个答案:

答案 0 :(得分:1)

我会这样写:

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])

答案 1 :(得分:0)

你的怀疑是正确的。如果string包含一些长度更长和更长的子串,那么你将全部输出

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

if increase > longest:
           longest = increase
           beststart = i-longest
           bestend = i+1
           increase = 0

答案 2 :(得分: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])