Thursday, April 14, 2016

LeetCode Q243: Shortest Word Distance

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = “coding”word2 = “practice”, return 3.
Given word1 = "makes"word2 = "coding", return 1.
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

Solution:

class Solution {
public:
int shortestDistance(vector<string>& words, string word1, string word2) {
int p1=-1*words.size(), p2=-1*words.size();
int sdist=words.size()-1;
for(int i=0; i<words.size(); i++){
if(words[i]==word1){
p1=i;
sdist=min(sdist, abs(p2-p1));
continue;
}
if(words[i]==word2){
p2=i;
sdist=min(sdist, abs(p2-p1));
continue;
}
}
return sdist;
}
};


Round 2 solutoin:
class Solution {
public:
int shortestDistance(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++){
pos1 = words[i]==word1? i:pos1;
pos2 = words[i]==word2? i:pos2;
dist = min(dist, abs(pos2-pos1));
}
return dist;
}
};
view raw Q243Rnd2.cpp hosted with ❤ by GitHub

No comments:

Post a Comment