Precise 10 lines C++ solution


  • 0
    V

    The main concept here is to use 2 pointers. One points to w1 and other keeps chasing it. The important thing to note is when it moves to next w1, how w2i is reset to past index is should start looking.

    int shortestWordDistance(vector<string>& w, string w1, string w2) {
            int w1i = 0, w2i = 0, n = w.size(), ans = n;
                
            while (w1i < n) {
                while (w1i < n && w[w1i] != w1)
                    w1i++;
                if (w1i == n)
                    return ans;
                w2i = (w1i - ans + 1) >= 0 ? (w1i - ans + 1) : 0; // this is best w2i ~ w1i can improve
                while (w2i < n && abs(w2i - w1i) <= ans) {
                    if (w1i != w2i && w[w2i] == w2)
                        ans = min(ans, abs(w2i - w1i));
                    w2i++;
                }
                w1i++;
            }
            return ans;
            
        }
    

Log in to reply
 

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