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 must be environment friendly.
The enter will solely include 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
Choice 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)
Choice 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 a part of(ok).cut up(), key=len)
Choice 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
check.assert_equals(longest('asd'), 'as')
check.assert_equals(longest('nab'), 'ab')
check.assert_equals(longest('abcdeapbcdef'), 'abcde')
check.assert_equals(longest('asdfaaaabbbbcttavvfffffdf'), 'aaaabbbbctt')
check.assert_equals(longest('asdfbyfgiklag'), 'fgikl')
check.assert_equals(longest('z'), 'z')
check.assert_equals(longest('zyba'), 'z')