# 243. Shortest Word Distance

Given a list of words and two words  word1  and  word2 , return the shortest distance between these two words in the list.

Example:
Assume that words = `["practice", "makes", "perfect", "coding", "makes"]`.

``````Input: _word1_ = “coding”, _word2_ = “practice”
Output: 3

Input: _word1_ = "makes", _word2_ = "coding"
Output: 1
``````

Note:
You may assume that  word1  does not equal to  word2 , and  word1  and  word2  are both in the list.

``````class Solution {
public:
int shortestDistance(vector<string>& words, string word1, string word2) {
vector<int> idx1, idx2;
int res = INT_MAX;
for (int i = 0; i < words.size(); ++i) {
if (words[i] == word1) idx1.push_back(i);
else if (words[i] == word2) idx2.push_back(i);
}
for (int i = 0; i < idx1.size(); ++i) {
for (int j = 0; j < idx2.size(); ++j) {
res = min(res, abs(idx1[i] - idx2[j]));
}
}
return res;
}
};
``````

``````class Solution {
public:
int shortestDistance(vector<string>& words, string word1, string word2) {
int p1 = -1, p2 = -1, res = INT_MAX;
for (int i = 0; i < words.size(); ++i) {
if (words[i] == word1) p1 = i;
else if (words[i] == word2) p2 = i;
if (p1 != -1 && p2 != -1) res = min(res, abs(p1 - p2));
}
return res;
}
};
``````

``````class Solution {
public:
int shortestDistance(vector<string>& words, string word1, string word2) {
int idx = -1, res = INT_MAX;
for (int i = 0; i < words.size(); ++i) {
if (words[i] == word1 || words[i] == word2) {
if (idx != -1 && words[idx] != words[i]) {
res = min(res, i - idx);
}
idx = i;
}
}
return res;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/243

Shortest Word Distance II

https://leetcode.com/problems/shortest-word-distance/

https://leetcode.com/problems/shortest-word-distance/discuss/66931/AC-Java-clean-solution

https://leetcode.com/problems/shortest-word-distance/discuss/66939/Java%3A-only-need-to-keep-one-index

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation