-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path243.cpp
More file actions
35 lines (29 loc) · 675 Bytes
/
243.cpp
File metadata and controls
35 lines (29 loc) · 675 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
35
/*
* Written by Nitin Kumar Maharana
* nitin.maharana@gmail.com
*/
class Solution {
public:
int shortestDistance(vector<string>& words, string word1, string word2) {
int word1Index, word2Index;
int dist;
word1Index = word2Index = -1;
dist = words.size();
for(int i = 0; i < words.size(); i++)
{
if(words[i] == word1)
{
word1Index = i;
if(word2Index != -1)
dist = ((word1Index - word2Index) < dist) ? (word1Index - word2Index) : dist;
}
else if(words[i] == word2)
{
word2Index = i;
if(word1Index != -1)
dist = ((word2Index - word1Index) < dist) ? (word2Index - word1Index) : dist;
}
}
return dist;
}
};