My 13 lines Simple Java Solution


  • 0
    public int shortestWordDistance(String[] words, String word1, String word2) {
        int min = words.length-1, word1Index = words.length-1, word2Index = words.length-1;
        for(int i=0; i<words.length; i++) {
            if(words[i].equals(word1)) {                            //find word1
                if(word1.equals(word2)) min = Math.min(min, Math.abs(i - word1Index));
                else min = Math.min(min, Math.abs(i - word2Index));
                word1Index = i;
            }
            if(words[i].equals(word2) && !word1.equals(word2)) {    //find word2
                min = Math.min(min, Math.abs(i - word1Index));
                word2Index = i;
            }
        }
        return min;
    }
    

    Main Idea:

    1. Initialize the min and two indexes to the length of array, so after updating any index, the min value must be smaller.
    2. Update corresponding index when its word is found, and update the min value.

Log in to reply
 

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