假设我有一串小写字母,例如:连续字母的最长序列
'ablccmdnneofffpg'
而且我的目标就是要找到连续数字的此字符串在这种情况下是里面的最长序列:
'abcdefg'
直观尝试找到解决每个字母循环,并获得最长从那个字母开始的序列。一种可能的解决方案是
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
是否有任何其他解决问题的方法较少,甚至使用某些pythonic方法?
你想查找_longest sequence_或这样一个序列的_length_吗? –
你的算法使用cpu周期。你可以一次追踪所有可能的序列,然后只需要为cpu交易内存就迭代一次。 – Harvey