244. Shortest Word Distance II

Problem:

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. Your method will be called repeatedly many times with different parameters. 

Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1

Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

Solutions:

class WordDistance {
public:
    WordDistance(vector<string>& words) {
        for (int i = 0; i < words.size(); ++i) {
            wordToIndex[words[i]].push_back(i);
        }
    }

    int shortest(string word1, string word2) {
        return shortest(wordToIndex[word1], wordToIndex[word2]);
    }

    int shortest(vector<int>& list1, vector<int>& list2) {
        int ret = INT_MAX;
        int pos1 = 0;
        int pos2 = 0;
        int last;
        int lastSource;

        if (list1[pos1] < list2[pos2]) {
            last = list1[pos1++];
            lastSource = 1;
        } else {
            last = list2[pos2++];
            lastSource = 2;
        }

        while (pos1 < list1.size() && pos2 < list2.size()) {
            if (list1[pos1] < list2[pos2]) {
                if (lastSource == 2) {
                    ret = min(ret, list1[pos1] - last);
                }
                last = list1[pos1++];
                lastSource = 1;
            } else {
                if (lastSource == 1) {
                    ret = min(ret, list2[pos2] - last);
                }
                last = list2[pos2++];
                lastSource = 2;
            }
        }

        if (pos1 == list1.size()) {
            ret = min(ret, list2[pos2] - last);
        } else {
            ret = min(ret, list1[pos1] - last);
        }

        return ret;
    }

private:
    unordered_map<string, vector<int>> wordToIndex;
};

/**
 * Your WordDistance object will be instantiated and called as such:
 * WordDistance* obj = new WordDistance(words);
 * int param_1 = obj->shortest(word1,word2);
 */

results matching ""

    No results matching ""