I was working on a problem set and I came across this problem:
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, ifs = '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 printLongest substring in alphabetical order is: abc
I actually was able to get a solution, but it was the most inefficient ever! And here's what I came up with:
def test():
index = 1
prev_index = 0
count = 0
global largest
largest = ''
test = s[prev_index]
while count < len(s):
if ord(s[index]) > ord(s[prev_index]):
test += s[index]
index += 1
prev_index += 1
elif ord(s[index]) == ord(s[prev_index]):
test += s[index]
index += 1
prev_index += 1
else:
if len(largest) < len(test):
largest = test[:]
test = s[index]
prev_index += 1
index += 1
count += 1
return largest
try:
test()
except IndexError:
pass
finally:
print largest
Can anyone give me an example of better code that produces the same output?