My concise simple Java solution with explaination


  • 1
    T

    When word1 equals to word2, we can find the minimum distance with only one pointer(which is p1).
    Update min every time we find the same word.
    Other part of code is the same as Shortest Word Distance.

    public class Solution {
    public int shortestWordDistance(String[] words, String word1, String word2) {
        int p1 = -1,p2 = -1,min = Integer.MAX_VALUE;
        for(int i = 0; i < words.length; i++){
            if(words[i].equals(word1)){
                if(word1.equals(word2) && p1 != -1){
                    min = Math.min(min,i - p1);
                    p1 = i;
                }
                else{
                    p1 = i;
                }
            }
            else if(words[i].equals(word2)){
                p2 = i;
            }
            if(p1 != -1 && p2 != -1 && !word1.equals(word2)){
                min = Math.min(min,Math.abs(p1 - p2));
            }
        }
        return min;
    }
    

    }


Log in to reply
 

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