My O(n) solution C++


  • 1
    Z
    class Solution {
    public:
        int shortestWordDistance(vector<string>& words, string word1, string word2) {
            int x=-1,y=-1;
            int shortest = INT_MAX;
            for(int i=0;i<words.size();i++){
                if(words[i]==word1){
                    if(word1==word2){
                        swap(x,y);
                    }
                    x = i;
                } 
                else if(words[i]==word2) y = i;
                if(abs(x-y)<=max(x,y)){
                    shortest = min(shortest,abs(x-y));
                }
    
            }
            return shortest;
        }
    };

Log in to reply
 

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