leedcode 排列组合问题解法-最小子串

54 阅读1分钟
# 最小子串 a = "12323566869794702" b = "972"  result="94702"
import itertools

a = "90072902453982"
b = "972"

b_dict = {i: [] for i in b}
lens = len(a)
for i in range(0, lens):
    if b_dict.get(a[i]) == [] or b_dict.get(a[i]) is not None:
        b_dict[a[i]].append(i)

# 排列组合方法 itertools.product([1,2], [3,4]) -->  (1,3), (1,4), (2,3), (2,4)
c = itertools.product(*list(b_dict.values()))
d = []
for i in c:
    i = list(i)
    i.sort()
    d.append(a[i[0]:i[-1] + 1])
print(d)
e = d[0]
for j in d:
    if len(j) < len(e):
        e = j
print(e)
  • result
['90072', '90072902', '90072902453982', '729', '72902', '72902453982', '729024539', '729024539', '72902453982']

729