Sharing my 20ms C++ solution


  • 0
    T
    class Solution {
    public:
        int shortestWordDistance(vector<string>& words, string word1, string word2) {
            vector<int> index1;
            vector<int> index2;
            int n = words.size(), i;
            for(i=0; i<n; i++)
            {
                if(words[i]==word1)
                    index1.push_back(i);
                if(words[i]==word2)
                    index2.push_back(i);
            }
            
            int distance = INT_MAX;
            for(int j=0; j<index1.size(); j++)
                for(int k=0; k<index2.size(); k++)
                    if(abs(index1[j]-index2[k])>0)
                        distance = min(distance, abs(index1[j]-index2[k]));
                        
            return distance;
        }
    };

Log in to reply
 

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