Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order.
For example, if s = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print
Longest substring in alphabetical order is: abc
Here's the code I found. How do I implement the latter condition in the question given above regarding ties?
*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)))*
I'd approach the problem the following way:
current
string of increasing letters and the currentlylongest
string.s
(starting with the second character).c
fulfills the requirementc >= current[-1]
, we add it to the current solution.current
string aslongest
.c
does not fulfill the ordering requirement, we start with a new solutioncurrent = c
.longest
string.How to fix your code wrt. the mentioned condition:
Use
>
instead of>=
in the comparisonlen(result) >= len(final)
, i.e. only update thefinal
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. (Movingelse:
two lines down was sufficient.)