在 Python 中查找显示字符 c 与该索引的最近距离的列表的程序
假设我们有一个字符串s和另一个字符c,c必须存在于s中,我们必须找到一个长度与s长度相同的列表,其中对于每个索引i,其值设置为与s[i]的最近距离C。
因此,如果输入类似于s="ppqppq"c="q",那么输出将是[2,1,0,1,1,0]
示例
让我们看下面的实现来更好地理解
def solve(s, c):
j = len(s)
d = [j - 1] * j
x = s.index(c)
for i in range(j):
if s[i] == c and i > x:
x = i
ind = 1
while True:
if d[x - ind] > ind:
d[x - ind] = ind
else:
break
ind += 1
d[i] = abs(x - i)
return d
s = "ppqppq"
c = "q"
print(solve(s, c))输入
"ppqppq", "q"输出结果
[2, 1, 0, 1, 1, 0]