Print the longest alphabetical substring using Python and for ties, print the first substring [duplicate]

走远了吗. 提交于 2019-12-02 01:49:18

I'd approach the problem the following way:

  • Let's define two strings: The current string of increasing letters and the currently longest string.
  • Both strings are initialized with the first letter. (This way we can always read their last letter.)
  • Then we iterate over the input string s (starting with the second character).
  • If the current character c fulfills the requirement c >= current[-1], we add it to the current solution.
  • We possibly store the current string as longest.
  • If c does not fulfill the ordering requirement, we start with a new solution current = c.
  • Finally, we print the longest string.
s = "azcbobobegghakl"
longest = s[0]
current = s[0]
for c in s[1:]:
    if c >= current[-1]:
        current += c
        if len(current) > len(longest):
            longest = current
    else:
        current = c
print "Longest substring in alphabetical order is:", longest

How to fix your code wrt. the mentioned condition:

Use > instead of >= in the comparison len(result) >= len(final), i.e. only update the final solution if it is longer, but not if it has the same length.


Considering Dylans comment

You're right. I updated both code and description to correctly handle the case when s ends with the longest alphabetical substring. (Moving else: two lines down was sufficient.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!