Skip to content Skip to sidebar Skip to footer

Finding The Longest Alphabetical Order Substring In A Longer Stringer

I have made a few attempts at writing this code but it isn't consistently solving the problem. Most often it will not output the first and last characters in the string. I am not s

Solution 1:

Python is much easier if you can avoid using indexes in loops. It's designed to make that easy because indexes lend themselves to hard-to-see off-by-one errors. For example, in your code you never use s[x] so you always miss the first letter of the string.

One way to tackle this is to keep track of the last letter seen in a variable. Initialize that with the first letter and then iterate the rest. It then becomes pretty readable:

s = 'abcdekyuuhhoowhoiwv'

# initialize
last = s[0]
current = last
longest = last

# loop letters starting at the second
for letter in s[1:]:
    if letter >= last:
        current += letter    
    else:
        current = letter  
    if len(current) > len(longest):
        longest = current

    last = letter

print(longest)
# 'abcdeky'

Also, I didn't test for an empty string above, but you probably should if there's any chance of one.


Solution 2:

I am using dynamic programming. And also my solution outputs many solution if present.

s = input()

a = [1]

for i in range(1,len(s)):
    if ord(s[i-1]) <= ord(s[i]):
        a.append(a[-1]+1)
    else:
        a.append(1)
m = max(a)
am = [i for i, x in enumerate(a) if x == m]

for i in am:
    ans = ""
    for j in range(i,i-m,-1):
        ans = s[j] + ans
    print(ans)

Testcases

Input

abcdekyuuhhoowhoiwv

Output

abcdeky

Input

abcdekabcdef

Output

abcdek
abcdef

Post a Comment for "Finding The Longest Alphabetical Order Substring In A Longer Stringer"