245. Shortest Word Distance III

This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.

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.

For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Given word1 = “makes”, word2 = “coding”, return 1. Given word1 = "makes", word2 = "makes", return 3.

public class Solution {
    public int shortestWordDistance(String[] words, String word1, String word2) {
        if(word1.equals(word2)){
            return shortest(words, word1);
        }else{
            int s = Integer.MAX_VALUE;
            int l = -1;
            int r = -1;
            for(int i=0 ; i< words.length; i++){
                if(word1.equals(words[i])) l=i;
                else if(word2.equals(words[i])) r=i;

                if(l>=0 && r>=0) s = Math.min(s, Math.abs(l - r));
            }
            return s;
        }
    }
    int shortest(String[] w, String needle){
        int k = -1;
        int s = Integer.MAX_VALUE;
        for(int i=0; i< w.length; i++){
            if(needle.equals(w[i])){
                if(k>=0) s = Math.min(s, i-k);
                k = i;
            }
        }
        return s;
    }
}

folloing is a better solution. you use l and r to track:

  • if word1 == word2, then l is current index, and r will be previous index.
  • if not equal, then l and r is for differnt word
public class Solution {
    public int shortestWordDistance(String[] words, String word1, String word2) {
        int l=-1, r= -1;
        int s = Integer.MAX_VALUE;
        for(int i=0; i< words.length; i++){
            if(word1.equals(words[i])){
                l = i;
                if( l >=0 && r >=0){
                    //if word1 == word2, then r is the last index, and l is current index;
                    s = l ==r ? s : Math.min(s, Math.abs(l-r)); 
                }
            }
            if(word2.equals(words[i])){
                r = i;
                if(l >=0 && r >=0){
                    s = l ==r ? s : Math.min(s, Math.abs(l-r));
                }
            }
        }

        return s;
    }
}

results matching ""

    No results matching ""