【发布时间】:2018-07-06 21:22:42
【问题描述】:
到目前为止,我有:
s = 'azcbobobegghakl'
i = 0
j = 1
temp = '' #temporary variable I use to change longest
longest = ''
for b in range(len(s)):
if s[i] <= s[j]: #checks if it's in alphabetical order
temp+=s[i]
if len(longest) < len(temp):
longest = temp
else:
temp = '' #reset temp after every substring
if len(longest) < len(temp):
longest += temp #update longest if the new substring is longer
i +=1
if j < len(s) - 1 : # because otherwise i get an IndexError
j +=1
print('Longest substring in alphabetical order is:', longest)
现在我的问题是我总是得到正确的字符串但没有最后一个字母。 (例如,这里不是“beggh”,而是“begg”)。
我还必须做到,如果是平局,第一个算作最长的(如果 s = abcbcd,abc 应该是最长的)
最后我知道这个问题已经在这里被问过好几次了,但我想尽可能修复我想出的代码,而不是完全使用别人的代码。
【问题讨论】:
-
如果我一直在思考你的代码,我会头疼的。有太多的事情在我的思维方式中没有意义。只需要几个一般提示:不要使用
i和j,使用i和i+1。为避免最后出现 IndexError,不要迭代range(len(s)),迭代range(len(s)-1)。最后,不要遍历b。b不用于其他任何用途。遍历i。这种变化会清理很多东西和困难。 -
@ti7
findall到底如何找到按字母顺序排列的字符串? -
@Poshi 感谢您的建议。希望现在可以更好地理解。
-
更好。但是您不必初始化
i,它会在for循环中被覆盖。增量相同,它将被for循环的下一次迭代覆盖。 -
@NikolaiTh3KillerKirilov 请不要根据给出的答案更新您的问题。否则,这些答案对未来的用户毫无意义。
标签: python python-3.x alphabetical longest-substring