Thursday, April 14, 2016

LeetCode Q244: Shortest Word Distance II

This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it?
Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and 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.

Solution:

class WordDistance {
public:
WordDistance(vector<string>& words) {
int loc=0;
unordered_map<string, int>::const_iterator it;
for(int i=0; i<words.size(); i++){
it = str2Idx.find(words[i]);
if(it==str2Idx.end()){
str2Idx[words[i]]=loc;
vector<int> newWord;
newWord.push_back(i);
locsOfStr.push_back(newWord);
loc++;
}else{
int loc = str2Idx[words[i]];
locsOfStr[loc].push_back(i);
}
}
}
int shortest(string word1, string word2) {
int i1=str2Idx[word1];
int i2=str2Idx[word2];
vector<int> locsStr1 = locsOfStr[i1];
vector<int> locsStr2 = locsOfStr[i2];
int sDist=INT_MAX;
for(int i=0; i<locsStr1.size(); i++)
for(int j=0; j<locsStr2.size(); j++){
sDist=min(sDist, abs(locsStr1[i]-locsStr2[j]));
}
return sDist;
}
unordered_map<string, int> str2Idx;
vector<vector<int> > locsOfStr;
};
// Your WordDistance object will be instantiated and called as such:
// WordDistance wordDistance(words);
// wordDistance.shortest("word1", "word2");
// wordDistance.shortest("anotherWord1", "anotherWord2");
view raw Q244.cpp hosted with ❤ by GitHub


Round 2 solution:
class WordDistance {
public:
WordDistance(vector<string>& words) {
for(int i=0; i<words.size(); i++){
auto it = myMap.find(words[i]);
if(it==myMap.end()){
vector<int> newVec={i};
myMap[words[i]]=newVec;
}else
myMap[words[i]].push_back(i);
}
}
int shortest(string word1, string word2) {
vector<int> vec1 = myMap[word1];
vector<int> vec2 = myMap[word2];
int minv = INT_MAX;
for(auto a: vec1)
for(auto b: vec2)
minv = min(minv, abs(a-b));
return minv;
}
unordered_map<string, vector<int> > myMap;
};
// Your WordDistance object will be instantiated and called as such:
// WordDistance wordDistance(words);
// wordDistance.shortest("word1", "word2");
// wordDistance.shortest("anotherWord1", "anotherWord2");
view raw Q244Rnd2.cpp hosted with ❤ by GitHub

No comments:

Post a Comment