Skip to content

Instantly share code, notes, and snippets.

@xzhang311
Created June 27, 2016 16:53
class Solution {
public:
int shortestWordDistance(vector<string>& words, string word1, string word2) {
int dist = INT_MAX;
int pos1 = -words.size();
int pos2 = words.size();
for(int i=0; i<words.size(); i++){
if(words[i]==word1){
dist = word1==word2? min(dist, abs(i-pos1)):min(dist, abs(i-pos2));
pos1 = i;
}
if(words[i]==word2){
dist = word1==word2? min(dist, abs(i-pos2)):min(dist, abs(i-pos1));
pos2 = i;
}
}
return dist;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment