Simple Java Solution


  • 0
    C
     public int shortestWordDistance(String[] words, String word1, String word2) {
            int min = Integer.MAX_VALUE;
            int i=-1, j=-1;
            for(int k=0;k<words.length;k++){
                if(words[k].equals(word1)){
                    if(word1.equals(word2)){
                        i=j;
                        j=k;
                    }
                    else i=k;
                }
                if(words[k].equals(word2)) j=k;   
                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.