用 Python 编写程序检查我们是否能站在距离最近联系人至少 k 的距离处
pythonserver side programmingprogramming更新于 2026/1/6 23:08:17
假设我们有一个字符串 s 和一个数字 k。现在字符串中的每个字符都是点(".")或"x",其中点表示空格,"x"表示人。我们必须检查是否可以选择一个站立的位置,使得我们与距离我们最近的人之间的距离至少为 k。 (此处每个相邻索引之间的距离为 1)。
因此,如果输入为 s = "x...x..", k = 2,则输出将为 True,因为我们可以站在 s[2] 或 s[6]。
为了解决这个问题,我们将遵循以下步骤 −
- pos := x 在 s 中的位置,如果不存在,pos 将为 -1
- 如果 pos 与 -1 相同或 pos>=k,则
- 返回 True
- last_x := pos
- dist_min := 2*k-1
- 进行无限循环,执行
- next_x := x 在 s 中的位置(从索引开始) last_x+1 到结束(如果 x 不存在,则为 -1)
- 如果 next_x 不等于 -1,则
- 如果 next_x-last_x-1 >= dist_min,则
- 返回 True
- last_x := next_x
- 如果 next_x-last_x-1 >= dist_min,则
- 否则,
- 如果 s 的大小 -last_x-1 >= k,则
- 返回 False
- 如果 s 的大小 -last_x-1 >= k,则
- 返回 null
让我们看看下面的实现以便更好地理解 −
示例
class Solution:
def solve(self, s, k):
pos = s.find("x")
if pos==-1 or pos>=k: return True last_x = pos
dist_min = 2*k-1
while True:
next_x = s.find("x", last_x+1)
if next_x!=-1:
if next_x-last_x-1 >= dist_min:
return True
last_x = next_x
else:
if len(s)-last_x-1>=k: return True
return False
return None
ob = Solution() print(ob.solve("x...x..", 2))
输入
"x...x..", 2
输出
True
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

