# coding=utf-8
import sys
def lists_combination(lists, code=''):
'''输入多个列表组成的列表, 输出其中每个列表所有元素可能的所有排列组合
code用于分隔每个元素'''
try:
import reduce
except:
from functools import reduce
def myfunc(list1, list2):
return [str(i) + ',' + str(j) for i in list1 for j in list2]
return reduce(myfunc, lists)
def solution(long_string, alphabet):
# 将所需查找字符分隔,放入alphaNeedFind列表中
alphaNeedFind = []
strFindPlaceGroup = []
for temp in alphabet:
alphaNeedFind.append(temp)
strFindPlaceGroup.append([])
# 将查找字符串分割并分别将各所需查找字符放入该分类组中,只以在原字符串位置表示
place = 0
for temp in long_string:
for alphaindex in range(len(alphaNeedFind)):
if alphaNeedFind[alphaindex] == temp:
strFindPlaceGroup[alphaindex].append(place)
place += 1
# 利用reduce函数将数组位置标识序号排序
groupsList = lists_combination(strFindPlaceGroup)
# 将字符串数组分成数字列表
list = []
i = 0
for group in groupsList:
list.append([])
for num in group.split(','):
list[i].append(int(num))
i += 1
# 对所有组合计算最短子字符串及长度
finalList = [0, 0] # 保存最短子字符串开头末尾序号
MinDistance = None # 保存最短子字符串长度
for x in list:
if MinDistance is None:
MinDistance = max(x) - min(x)
finalList[0] = min(x)
finalList[1] = max(x)
if max(x) - min(x) < MinDistance:
MinDistance = max(x) - min(x)
finalList[0] = min(x)
finalList[1] = max(x)
return long_string[finalList[0]:finalList[1] + 1]
if __name__ == "__main__":
# 读取第一行的n
long_string = 'eeaaccebce-abc'
alphabet = 'abc'
print(solution(long_string, alphabet))
求覆盖最短字符串
最新推荐文章于 2024-11-09 15:42:25 发布