Simple C++ solution


  • 0
    L
    class WordDistance 
    {
     private:
        unordered_map<string, vector<int>> table;
        int FindMinDistance(vector<int> & indices1, vector<int> & indices2)
        {
            int minD = INT_MAX;
            int i,j;
            i = j = 0;
            
            while(i < indices1.size() && j < indices2.size())
            {
                int diff = abs(indices1[i] - indices2[j]);
                if(indices1[i] < indices2[j]) ++i;
                else ++j;
                
                minD = min(minD, diff);
            }
            return minD;
        }
        
    public:
        WordDistance(vector<string>& words)
        {
            for(int i = 0; i < words.size(); ++i) 
                table[words[i]].push_back(i);
        }
        int shortest(string word1, string word2) 
        {
            return FindMinDistance(table[word1], table[word2]);
        }
    };

Log in to reply
 

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