-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path245_Shortest-Word-Distance-III.cpp
More file actions
44 lines (42 loc) · 1.3 KB
/
245_Shortest-Word-Distance-III.cpp
File metadata and controls
44 lines (42 loc) · 1.3 KB
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
class Solution {
public:
int shortestWordDistance(vector<string>& wordsDict, string word1, string word2) {
int dist = INT_MAX;
int idx1 = -1, idx2 = -1;
bool isSame = word1 == word2;
for(int i = 0; i < wordsDict.size(); ++i){
if(wordsDict[i] == word1) idx1 = i;
if(wordsDict[i] == word2){
if(isSame) idx1 = idx2;
idx2 = i;
}
if(idx1 != -1 && idx2 != -1) dist = min(dist, abs(idx1 - idx2));
}
return dist;
}
};
class Solution {
public:
int shortestWordDistance(vector<string>& wordsDict, string word1, string word2) {
int n = wordsDict.size(), dist = INT_MAX;
if(word1 == word2){
int prev = -1;
for(int i = 0; i < n; ++i){
if(wordsDict[i] == word1){
if(prev != -1){
dist = min(dist, i - prev);
}
prev = i;
}
}
return dist;
}
int idx1 = -1, idx2 = -1;
for(int i = 0; i < n; ++i){
if(wordsDict[i] == word1) idx1 = i;
if(wordsDict[i] == word2) idx2 = i;
if(idx1 != -1 && idx2 != -1) dist = min(dist, abs(idx1 - idx2));
}
return dist;
}
};