Straightforward C++ solution


  • 1
    J
    int shortestWordDistance(vector<string>& words, string word1, string word2) {
        int minDist = INT_MAX;
        
        if(word1 != word2) {
            int pos1 = INT_MAX, pos2 = INT_MAX;
            for(int i = 0; i<words.size(); i++) {
                if(words[i] == word1)
                    pos1 = i;
                if(words[i] == word2)
                    pos2 = i;
                
                if(pos1 != INT_MAX && pos2 != INT_MAX)
                    minDist = min(minDist, abs(pos1 - pos2));
            }
        }
        else {
            int pos = INT_MAX;
            for(int i = 0; i<words.size(); i++) {
                if(words[i] == word1) {
                    if(pos != INT_MAX)
                        minDist = min(minDist, i - pos);
                    pos = i;
                }
            }
        }
        
        return minDist;
    }

Log in to reply
 

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