[LeetCode] Shortest Word Distance III

245. Shortest Word Distance III

Given an array of strings wordsDict and two strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list.

Note that word1 and word2 may be the same. It is guaranteed that they represent two individual words in the list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int shortestWordDistance(vector<string>& wordsDict, string word1, string word2) {
vector<int> A, B;
for(int i = 0; i < wordsDict.size(); i++) {
if(wordsDict[i] == word1) A.push_back(i);
else if(wordsDict[i] == word2) B.push_back(i);
}
int res = INT_MAX;
if(word1 == word2) {
for(int i = 0; i < A.size() - 1; i++) {
res = min(res, A[i + 1] - A[i]);
}
} else {
for(int i = 0, j = 0; i < A.size(); i++) {
while(j < B.size() and B[j] < A[i]) j++;
if(j) res = min(res, A[i] - B[j - 1]);
if(j != B.size()) res = min(res, B[j] - A[i]);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/10/PS/LeetCode/shortest-word-distance-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.