我想使用python查找连续字母的最长子串。
def f(word):
'''
Recall that if c is an ascii character then ord(c) returns its ascii code.
Will be tested on nonempty strings of lowercase letters only.
>>> f('x')
The longest substring of consecutive letters has a length of 1.
The leftmost such substring is x.
>>> f('xy')
The longest substring of consecutive letters has a length of 2.
The leftmost such substring is xy.
>>> f('ababcuvwaba')
The longest substring of consecutive letters has a length of 3.
The leftmost such substring is abc.
>>> f('abbcedffghiefghiaaabbcdefgg')
The longest substring of consecutive letters has a length of 6.
The leftmost such substring is bcdefg.
>>> f('abcabccdefcdefghacdef')
The longest substring of consecutive letters has a length of 6.
The leftmost such substring is cdefgh.
'''
desired_length = 0
desired_substring = ''
print(f'The longest substring of consecutive letters has a length of {desired_length}.')
print(f'The leftmost such substring is {desired_substring}.')
if __name__ == '__main__':
import doctest
doctest.testmod()
如何解决此问题?
答案 0 :(得分:1)
from itertools import count
def f(input_string):
maxsubstr = input_string[0:0]
for start in range(len(input_string)):
for end in count(start + len(maxsubstr) + 1):
substr = input_string[start:end]
if len(set(substr)) != (end - start):
break
if (ord(max(substr)) - ord(min(substr)) + 1) == len(substr):
maxsubstr = substr
print ('The longest substring of consecutive letters has a length of {}.'.format(len(maxsubstr)))
print ('The leftmost such substring is {}.'.format(maxsubstr))
f('x')
f('xy')
f('ababcuvwaba')
f('abbcedffghiefghiaaabbcdefgg')
f('abcabccdefcdefghacdef')
输出:
The longest substring of consecutive letters has a length of 1.
The leftmost such substring is x.
The longest substring of consecutive letters has a length of 2.
The leftmost such substring is xy.
The longest substring of consecutive letters has a length of 3.
The leftmost such substring is abc.
The longest substring of consecutive letters has a length of 6.
The leftmost such substring is bcdefg.
The longest substring of consecutive letters has a length of 6.
The leftmost such substring is cdefgh.