2017-07-03 69 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])