Clear c++ solution (not as concise, but clear :-)


  • 0
    H

    easy to understand

    int shortestWordDistance(vector<string>& words, string word1, string word2) {

        int n = words.size();
        unordered_map<string,int> mp;
        int minlen = n;
        
        int word1idx = -1, word2idx = -1, curlen = n, pre = -1;
        
        for(int i=0; i<words.size(); i++){
            
            if(words[i] == word1 && words[i] ==word2){
                 
                 if(pre !=-1){
                     curlen = abs(i-pre);
                 }
                 pre = i;
                 
            }else if(words[i] == word1){
                
                    if(word2idx!=-1 ){
                       curlen = abs(i-word2idx);
                    }
                
                word1idx = i;
                
            }else if(words[i] == word2){
                
                if(word1idx!=-1 ){
                     curlen = abs(i-word1idx);
                }
                word2idx = i;
            }
        
            minlen = min(minlen,curlen);
        
        }
        
        
        return minlen;
        
    }

Log in to reply
 

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