用 Python 编写程序,查找显示字符 c 与该索引的最近距离的列表

pythonserver side programmingprogramming更新于 2025/12/17 15:40:17

假设我们有一个字符串 s 和另一个字符 c,c 必须存在于 s 中,我们必须找到一个长度与 s 长度相同的列表,其中对于每个索引 i,其值设置为 s[i] 与 c 的最近距离。

因此,如果输入为 s = "ppqppq" c = "q",则输出将为 [2, 1, 0, 1, 1, 0]

为了解决这个问题,我们将遵循以下步骤 −

  • j := s 的大小

  • d := [j - 1] * j

  • x := c 在 s 中的索引

  • 对于 0 到 j - 1 范围内的 i,执行

    • 如果 s[i] 与 c 相同且 i > x,然后

      • x := i, ind := 1

      • 循环执行以下内容,执行

        • 如果 d[x - ind] > ind,则

          • d[x - ind] := ind

        • 否则,

          • 退出循环

        • ind := ind + 1

    • d[i] := |x - i|

  • 返回 d

示例

让我们看看下面的实现以便更好地理解

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]

相关文章


有用资源