假设s是一个小写字符字符串。 编写一个程序,打印字母按字母顺序出现的s的最长子串。
例如,如果s='azcbobobebeghakl',那么您的程序应该打印
Longest substring in alphabetical order is: beggh
对于ties,打印第一个子字符串。例如,如果s='abcbcd',则程序应打印
Longest substring in alphabetical order is: abc
这是我找到的密码。在上面关于领带的问题中,我如何实现后一个条件?
*s = raw_input('provide string: ')
result = []
final = []
for letters in s:
result = result + [letters]
if result == sorted(result) and len(result) >= len(final):
final = result
elif result != sorted(result):
result = [result[len(result)-1]]
print('Longest substring in alphabetical order is: '+(''.join(final)))*
我会用下面的方法来解决这个问题:
current
字符串和当前的longest
字符串。s
(从第二个字符开始)。c
满足要求c >= current[-1]
,则将其添加到当前解决方案中。current
字符串存储为longest
。c
不满足排序要求,我们将从一个新的解决方案current = c
开始。longest
字符串。如何修复代码wrt。上述条件:
在比较中使用
>
而不是>=
,也就是说,仅当final
解决方案的长度时才更新它,但如果它的长度相同则不更新。考虑Dylans的评论
你说得对。当
s
以最长的字母顺序子字符串结尾时,我更新了代码和描述以正确处理这种情况。(向下移动两行就足够了。)相关问题 更多 >
编程相关推荐