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

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

因此,如果输入类似于text =“ cat dog abcd dog cat cat abcd dog wxyz”,word0 =“ abcd”,word1 =“ wxyz”,则输出将为1,因为在“ abcd”和“ wxyz”

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

  • word_list:=文本中的单词列表

  • ans:= word_list的大小

  • L:=空

  • 对于范围在0至word_list大小-1的R

    • 如果L不为null并且word_list [R]不是word_list [L],则

    • L:= R

    • ans:= ans和R-L-1的最小值

    • 如果word_list [R]是word0或word_list [R]是word1,则

    • 如果ans与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