s='cbaebabacd'
p='abc'
l=[]
answer = list()
count = 0
l = list([s[i] for i in range(j,j+len(p))] for j in range(len(s)-len(p)+1))
for i in l:
for j in range(len(p)):
k=list(p)
if i[j] in k:
k.remove(i[j])
if len(k)==0:
answer.append(count)
else:
continue
count += 1
break
print(answer)
这段代码的输出是"[]",但我认为对于字谜子串问题,它的输出应该是"[0,6]"。
唯一的问题是 k=list(p)
,它不应该在内部循环中,而应该在它之前。
s='cbaebabacd'
p='abc'
l=[]
answer = list()
count = 0
l = list([s[i] for i in range(j,j+len(p))] for j in range(len(s)-len(p)+1))
for i in l:
k=list(p)
for j in range(len(p)):
if i[j] in k:
k.remove(i[j])
if len(k)==0:
answer.append(count)
else:
continue
count += 1
break
print(answer)
输出。
[0, 6]