Python 中两个单词之间的最小距离

pythonserver side programmingprogramming更新于 2025/12/26 3:24:17

假设我们有两个字符串,word0 和 word1 以及一个文本。我们必须找到给定文本中 word0 和 word1 任意两次出现之间的最小距离。这里的距离以单词数来衡量。如果文本中不存在它们,则返回 -1。

因此,如果输入为文本 = "cat dog abcd dog cat cat abcd dog wxyz", word0 = "abcd", word1 = "wxyz",则输出将为 1,因为 "abcd" 之间有一个单词 "dog"和"wxyz"

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

  • word_list := 文本中的单词列表
  • ans := word_list 的大小
  • L := null
  • 对于范围为 0 到 word_list 大小 - 1 的 R,执行
    • 如果 word_list[R] 是 word0 或 word_list[R] 是 word1,则
      • 如果 L 不为 null 且 word_list[R] 不是 word_list[L],则
        • ans := ans 和 R - L - 1 的最小值
      • L := R
  • 如果与 word_list 的大小相同则返回 -1,否则

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

示例

class Solution:
   def solve(self, text, word0, word1):
      word_list = text.split()
      ans = len(word_list)
      L = None
      for R in range(len(word_list)):
         if word_list[R] == word0 or word_list[R] == word1:
            if L is not None and word_list[R] != word_list[L]:
               ans = min(ans, R - L - 1)
               L = R
      return -1 if ans == len(word_list) else ans
ob = Solution()
text = "cat dog abcd dog cat cat abcd dog wxyz"
word0 = "abcd"
word1 = "wxyz"
print(ob.solve(text, word0, word1))

输入

"cat dog abcd dog cat cat abcd dog wxyz", "abcd", "wxyz"

输出

1

相关文章


有用资源