-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.cpp
55 lines (51 loc) · 1.52 KB
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <algorithm>
#include <climits>
#include <cstddef>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
int shortestWordDistance(vector<string>& wordsDict,
const string& word1,
const string& word2) {
// Same similar as shortestWordDistanceTwo.
// Collect all indices of word1 and word2. Then linear search.
// word1 may be equal to word2. But it is guaranteed that they are at least
// two distinct words.
vector<int> indices1;
vector<int> indices2;
for (size_t i = 0; i < wordsDict.size(); ++i) {
if (wordsDict[i] == word1) {
indices1.push_back(i);
} else if (wordsDict[i] == word2) {
// Else is important to ensure that if word1 and word2 are the same,
// then only indices1 will be populated, allowing cleaner handling of
// this edge case.
indices2.push_back(i);
}
}
// find smallest adjacent distance
int range = INT_MAX;
if (word1 == word2) {
for (size_t i = 1; i < indices1.size(); ++i) {
range = min(range, indices1[i] - indices1[i - 1]);
}
return range;
}
// otherwise find smallest overlapping range.
int i = 0;
int j = 0;
while (i < indices1.size() && j < indices2.size()) {
const int idx1 = indices1[i];
const int idx2 = indices2[j];
range = min(range, abs(idx2 - idx1));
if (idx1 < idx2) {
++i;
} else {
++j;
}
}
return range;
}
};