Clean C++ 12 lines O(n) solution


  • 0
     int shortestDistance(vector<string>& words, string word1, string word2) {
            int distance=0;
            int minDT=INT_MAX;
            vector<string>::iterator it=words.begin();
            string next="";
            while(it!=words.end()){
                distance++;
                if(*it==next) minDT=min(minDT,distance),distance=0;
                if(*it==word1) distance=0,next=word2;
                if(*it==word2) distance=0,next=word1;
                it++;
            }
            return minDT;
        }
    

Log in to reply
 

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