2017-07-03 29 views
0

代码运行正常,输出看起来没问题。但我的print是里面的for循环,这让我怀疑的编码是正确的:编写一个程序,打印s中按字母顺序排列的字母的最长子串

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 
+0

感谢您的帮助! –

回答

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

你的怀疑是正确的。如果字符串包含有越来越长的长一些适当的子串,你会输出他们都

而是直接打印只记得指数i和长度longest(或子边界),并且输出循环之后的最好的字符串。

if increase > longest: 
      longest = increase 
      beststart = i-longest 
      bestend = i+1 
      increase = 0 
+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])