假设我有一串小写字母,例如
'ablccmdnneofffpg'
Run Code Online (Sandbox Code Playgroud)
我的目标是找到这个字符串中连续数字的最长序列,在这种情况下是:
'abcdefg'
Run Code Online (Sandbox Code Playgroud)
直观的尝试是在每个字母周围找到循环并从该字母开始获得最长的序列.一种可能的解决方案是
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
Run Code Online (Sandbox Code Playgroud)
有没有其他方法可以用更少的线来解决问题,甚至使用一些pythonic方法?
您可以使用字典跟踪字符串中所示的连续字符的所有子序列,然后选择长度最大的子序列.
每个子序列由字母表中的下一个候选键控,以便一旦在字符串中到达预期的候选者,它就用于更新字典中相应子序列的值并添加为由下一个字母键控的新字典值:
def longest_sequence(s):
d = {}
for x in s:
if x in d:
d[chr(ord(x)+1)] = d[x] + x
else:
d[chr(ord(x)+1)] = x
return max(d.values(), key=len)
print(longest_sequence('ablccmdnneofffpg'))
# abcdefg
print(longest_sequence('ba'))
# b
print(longest_sequence('sblccmtdnneofffpgtuyvgmmwwwtxjyuuz'))
# stuvwxyz
Run Code Online (Sandbox Code Playgroud)