-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path243_Shortest-Word-Distance.cpp
More file actions
34 lines (31 loc) · 979 Bytes
/
243_Shortest-Word-Distance.cpp
File metadata and controls
34 lines (31 loc) · 979 Bytes
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
class Solution {
public:
int shortestDistance(vector<string>& wordsDict, string word1, string word2) {
int dist = INT_MAX;
int idx1 = -1, idx2 = -1;
for(int i = 0; i < wordsDict.size(); ++i){
if(wordsDict[i] == word1){
idx1 = i;
if(idx2 != -1) dist = min(dist, idx1 - idx2);
}
if(wordsDict[i] == word2){
idx2 = i;
if(idx1 != -1) dist = min(dist, idx2 - idx1);
}
}
return dist;
}
};
class Solution {
public:
int shortestDistance(vector<string>& wordsDict, string word1, string word2) {
int dist = INT_MAX;
int idx1 = -1, idx2 = -1;
for(int i = 0; i < wordsDict.size(); ++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;
}x
};