-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path244.cpp
44 lines (40 loc) · 1.33 KB
/
244.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
__________________________________________________________________________________________________
class WordDistance {
public:
WordDistance(vector<string>& words) {
for (int i = 0; i < words.size(); ++i) {
m[words[i]].push_back(i);
}
}
int shortest(string word1, string word2) {
int res = INT_MAX;
for (int i = 0; i < m[word1].size(); ++i) {
for (int j = 0; j < m[word2].size(); ++j) {
res = min(res, abs(m[word1][i] - m[word2][j]));
}
}
return res;
}
private:
unordered_map<string, vector<int> > m;
};
__________________________________________________________________________________________________
class WordDistance {
public:
WordDistance(vector<string>& words) {
for (int i = 0; i < words.size(); ++i) {
m[words[i]].push_back(i);
}
}
int shortest(string word1, string word2) {
int i = 0, j = 0, res = INT_MAX;
while (i < m[word1].size() && j < m[word2].size()) {
res = min(res, abs(m[word1][i] - m[word2][j]));
m[word1][i] < m[word2][j] ? ++i : ++j;
}
return res;
}
private:
unordered_map<string, vector<int> > m;
};
__________________________________________________________________________________________________