245. Shortest Word Distance III (1)

Link

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

word1 and word2 may be the same and they represent two individual words in the list.

Example: Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1 = “makes”, word2 = “coding”
Output: 1
Input: word1 = "makes", word2 = "makes"
Output: 3

Note: You may assume word1 and word2 are both in the list.

Solution

Divide into two case : 1. word1 != word2 : same as Shortest Word Distance I 2. word1 == word2

public static int getShortestDistance(String[] words, String word1, String word2){
        int i = -1, j = -1, min = Integer.MAX_VALUE;
        for(int k = 0 ; k < words.length; k++){
            if(word1.equals(word2)){
                if(word1.equals(words[k])){
                    if(i != -1){
                        min = Math.min(min, k-i);
                    }
                    i = k;
                }
            }
            else{
                if(word1.equals(words[k])){
                    i = k;
                    if(j != -1){
                        min = Math.min(min, i-j);
                    }
                }
                else if (word2.equals(words[k])){
                    j = k;
                    if(i != -1){
                        min = Math.min(min, j-i);
                    }
                }
            }
        }
        return min;
    }

Last updated

Was this helpful?