# 245. Shortest Word Distance III

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

word1  and  word2  may be the same and they represent two individual words in the list.

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

``````Input: _word1_ = “makes”, _word2_ = “coding”
Output: 1

Input: _word1_ = "makes", _word2_ = "makes"
Output: 3
``````

Note:
You may assume  word1  and  word2  are both in the list.

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

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

``````class Solution {
public:
int shortestWordDistance(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 && (word1 == word2 || words[i] != words[idx])) {
res = min(res, i - idx);
}
idx = i;
}
}
return res;
}
};
``````

Github 同步地址：

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

Shortest Word Distance II

Shortest Word Distance

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

https://leetcode.com/problems/shortest-word-distance-iii/discuss/67097/12-16-lines-Java-C%2B%2B

https://leetcode.com/problems/shortest-word-distance-iii/discuss/67095/Short-Java-solution-10-lines-O(n)-modified-from-Shortest-Word-Distance-I

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

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

×

Help us with donation