The problem
Discover the longest substring in alphabetical order.
Instance:
the longest alphabetical substring in "asdfaaaabbbbcttavvfffffdf"
is "aaaabbbbctt"
.
Overview:
There are exams with strings as much as 10 000
characters lengthy so your code will should be environment friendly.
The enter will solely encompass lowercase characters and will likely be at the least one letter lengthy.
If there are a number of options, return the one which seems first.
The answer in Python
Possibility 1:
import re
reg = re.compile('a*b*c*d*e*f*g*h*i*j*ok*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*')
def longest(s):
return max(reg.findall(s), key=len)
Possibility 2:
def longest(s):
ok = []
for i in vary(len(s)-1):
if s[i] <= s[i+1]:
ok.append(s[i])
else:
ok.append(s[i])
ok.append(' ')
ok += s[-1]
return max(''.be part of(ok).break up(), key=len)
Possibility 3:
def longest(s):
chunks = []
for c in s:
if chunks and chunks[-1][-1] <= c:
chunks[-1] += c
else:
chunks.append(c)
return max(chunks, key=len)
Take a look at circumstances to validate our resolution
take a look at.assert_equals(longest('asd'), 'as')
take a look at.assert_equals(longest('nab'), 'ab')
take a look at.assert_equals(longest('abcdeapbcdef'), 'abcde')
take a look at.assert_equals(longest('asdfaaaabbbbcttavvfffffdf'), 'aaaabbbbctt')
take a look at.assert_equals(longest('asdfbyfgiklag'), 'fgikl')
take a look at.assert_equals(longest('z'), 'z')
take a look at.assert_equals(longest('zyba'), 'z')