Skip to content

Commit da6b681

Browse files
committed
Create shortest-word-distance-ii.cpp
1 parent 2683d80 commit da6b681

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Time: ctor: O(n), shortest: O(a + b), a, b is occurences of word1, word2
2+
// Space: O(n)
3+
4+
class WordDistance {
5+
public:
6+
WordDistance(vector<string> words) {
7+
for (int i = 0; i < words.size(); ++i) {
8+
wordIndex[words[i]].emplace_back(i);
9+
}
10+
}
11+
12+
int shortest(string word1, string word2) {
13+
const vector<int>& indexes1 = wordIndex[word1];
14+
const vector<int>& indexes2 = wordIndex[word2];
15+
16+
int i = 0, j = 0, dist = INT_MAX;
17+
while (i < indexes1.size() && j < indexes2.size()) {
18+
dist = min(dist, abs(indexes1[i] - indexes2[j]));
19+
indexes1[i] < indexes2[j] ? ++i : ++j;
20+
}
21+
return dist;
22+
}
23+
24+
private:
25+
unordered_map<string, vector<int>> wordIndex;
26+
};

0 commit comments

Comments
 (0)