The way to Discover the Longest Substring in Alphabetical Order in Python

The problem

Discover the longest substring in alphabetical order.


the longest alphabetical substring in "asdfaaaabbbbcttavvfffffdf" is "aaaabbbbctt".


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(' ')
    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
    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')

Leave a Reply

Your email address will not be published. Required fields are marked *