Skip to content

Commit 2683d80

Browse files
committed
Create shortest-word-distance-iii.cpp
1 parent ecb9889 commit 2683d80

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

C++/shortest-word-distance-iii.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int shortestWordDistance(vector<string>& words, string word1, string word2) {
7+
int dist = INT_MAX;
8+
for (int i = 0, index1 = -1, index2 = -1; i < words.size(); ++i) {
9+
if (words[i] == word1) {
10+
if (index1 != -1) {
11+
dist = min(dist, abs(index1 - i));
12+
}
13+
index1 = i;
14+
} else if (words[i] == word2) {
15+
index2 = i;
16+
}
17+
if (index1 != -1 && index2 != -1) {
18+
dist = min(dist, abs(index1 - index2));
19+
}
20+
}
21+
return dist;
22+
}
23+
};

0 commit comments

Comments
 (0)