Wednesday, February 21, 2024
HomeSoftware EngineeringFind out how to Discover the Longest Substring in Alphabetical Order in...

Find out how to Discover the Longest Substring in Alphabetical Order in Python


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 have to be environment friendly.

The enter will solely include lowercase characters and can be a minimum of 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*okay*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):
    okay = []
    for i in vary(len(s)-1):
        if s[i] <= s[i+1]:
            okay.append(s[i])
        else:
            okay.append(s[i])
            okay.append(' ')
    okay += s[-1]
    return max(''.be part of(okay).break 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 answer

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')
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments