Easy understand java solution


  • 0
    L
    public int shortestWordDistance(String[] words, String word1, String word2) {
            int i=-1, j=-1, min=Integer.MAX_VALUE;
            for(int w=0;w<words.length;w++){
            	int lastI=i;
            	if(words[w].equals(word1))
            		i=w;
            	if(words[w].equals(word2)){
            		if(lastI!=i)	j=lastI;//word1,2 are same
            		else	j=w;		  //normal situation
            	}
            	if(i!=-1&&j!=-1)
            		min=Math.min(min, Math.abs(i-j));
            }
            return min;
        }

Log in to reply
 

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