classSolution{public:intshortestWordDistance(vector<string>&words,stringword1,stringword2){constboolisSame=word1==word2;intans=INT_MAX;// If word1 == word2, index1 is the newest indexintindex1=words.size();// If word1 == word2, index2 is the previous indexintindex2=-words.size();for(inti=0;i<words.size();++i){if(words[i]==word1){if(isSame)index2=index1;index1=i;}elseif(words[i]==word2){index2=i;}ans=min(ans,abs(index1-index2));}returnans;}};
classSolution{publicintshortestWordDistance(String[]words,Stringword1,Stringword2){finalbooleanisSame=word1.equals(word2);intans=Integer.MAX_VALUE;intindex1=words.length;// If word1 == word2, index1 is the newest indexintindex2=-words.length;// If word1 == word2, index2 is the previous indexfor(inti=0;i<words.length;++i){if(words[i].equals(word1)){if(isSame)index2=index1;index1=i;}elseif(words[i].equals(word2)){index2=i;}ans=Math.min(ans,Math.abs(index1-index2));}returnans;}}
classSolution:defshortestWordDistance(self,wordsDict:List[str],word1:str,word2:str)->int:isSame=word1==word2ans=math.inf# If word1 == word2, index1 is the newest indexindex1=len(wordsDict)# If word1 == word2, index2 is the previous indexindex2=-len(wordsDict)fori,wordinenumerate(wordsDict):ifword==word1:ifisSame:index2=index1index1=ielifword==word2:index2=ians=min(ans,abs(index1-index2))returnans