假设我们有一个单词列表以及另外两个单词word1和word2,我们必须在列表中找到这两个单词之间的最短距离。这里的单词1和单词2可以相同,它们代表列表中的两个单独的单词。让我们假设单词= [“练习”,“成功”,“完美”,“技能”,“成功”]。
因此,如果输入类似于word1 =“ makes”,word2 =“ skill”,则输出将为1
为了解决这个问题,我们将遵循以下步骤-
ret:= 10 ^ 9,l1:= 10 ^ 9,l2:= -10 ^ 9
n:=字数
对于初始化i:= 0,当i <n时,更新(将i增加1),执行-
如果word1与word2相同,则-
l2:=我
l1:= l2
l1:=我
如果word [i]与word1相同,则-
如果word [i]与word2相同,则-
ret:= | l2-l1 |的最小值 然后退回
返回ret
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h> using namespace std; class Solution { public: int shortestWordDistance(vector<string<& words, string word1, string word2) { int ret = 1e9; int l1 = 1e9; int l2 = -1e9; int n = words.size(); for (int i = 0; i < n; i++) { if (words[i] == word1) { l1 = i; } if (words[i] == word2) { if (word1 == word2) { l1 = l2; } l2 = i; } ret = min(abs(l2 - l1), ret); } return ret; } }; main(){ Solution ob; vector<string< v = {"practice", "makes", "perfect", "skill", "makes"}; cout << (ob.shortestWordDistance(v, "makes", "skill")); }
{"practice", "makes", "perfect", "skill", "makes"},"makes", "skill"
输出结果
1