C++ O(n) solution.

  • 2
    int shortestWordDistance(vector<string>& words, string word1, string word2) {
        int res = words.size(), l = words.size(), r = -words.size();
        for (unsigned int i=0; i<words.size(); i++) {
            if (words[i] == word1)
                l = (word1==word2)?r:i;
            if (words[i] == word2) 
                r = i;
            res = min(res, abs(l-r));
        return res;

Log in to reply

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