56ms C++ solution


  • 1
    K
    class WordDistance {
    public:
        WordDistance(vector<string>& words) {
            for(int i=0; i<words.size(); ++i)
            {
                mp[words[i]].push_back(i);
            }
        }
    
        int shortest(string word1, string word2) {
            vector<int> w1 = mp[word1];
            vector<int> w2 = mp[word2];
            int res=INT_MAX;
            for(int i=0; i<w1.size(); ++i)
                for(int j=0; j<w2.size(); ++j)
                    res=(abs(w1[i]-w2[j])<res)? abs(w1[i]-w2[j]) : res;
            return res;
        }
    private:
        unordered_map<string, vector<int>> mp;
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.