Longest sequence of consecutive letters

Viewed 2681

Suppose I have a string of lower case letters, e.g.

'ablccmdnneofffpg'

And my aim is to find the longest sequence of the consecutive numbers inside this string which in this case is:

'abcdefg'

The intuitive attempt is to find loop around each letter and obtain the longest sequence starting from that letter. One possible solution is

longest_length = 0
start = None
current_start = 0
while current_start < len(word) - longest_length:
    current_length = 1
    last_in_sequence = ord(word[current_start])
    for i in range(current_start + 1, len(word)):
        if ord(word[i]) - last_in_sequence == 1:
            current_length += 1
            last_in_sequence = ord(word[i])
    if current_length > longest_length:
        longest_length = current_length
        start = current_start
    while (current_start < len(word) - 1 and
           ord(word[current_start + 1]) - ord(word[current_start]) == 1):
        current_start += 1
    current_start += 1

Are there any other ways of solving the problem with fewer lines, or even using some pythonic methods?

4 Answers
Related