Question

Formatted question description: https://leetcode.ca/all/245.html

 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.

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

 @tag-array

Algorithm

A condition is added here, that is, two words may be the same.

When word1 and word2 are equal, use p1 to save the result of p2, and p2 is assigned to the current position i, so that the result can be updated.

If word1 and word2 are not equal, the same logic is still valid.

Code

Java

  • public class Shortest_Word_Distance_III {
    
        public static void main(String[] args) {
            Shortest_Word_Distance_III out = new Shortest_Word_Distance_III();
            Solution s = out.new Solution();
    
            // output: 2
            System.out.println(
                s.shortestWordDistance(new String[]{"makes", "practice", "makes", "perfect", "coding", "makes"}, "makes", "makes"));
        }
    
    
        public class Solution {
            public int shortestWordDistance(String[] words, String word1, String word2) {
                int posA = -1;
                int posB = -1;
                int minDistance = Integer.MAX_VALUE;
    
                for (int i = 0; i < words.length; i++) {
                    String word = words[i];
    
                    if (word.equals(word1)) {
                        posA = i;
                    } else if (word.equals(word2)) {
                        posB = i; // this is covering normal cases, word1 not same as word2
                    }
    
                    if (posA != -1 && posB != -1 && posA != posB) { // @note: update before reset posB
                        minDistance = Math.min(minDistance, Math.abs(posA - posB));
                    }
    
                    if (word1.equals(word2)) {
                        // always updating posA in above line, so after checking update posB
                        // so that, posB is always the most recent word's index
                        posB = posA;
                    }
                }
    
                return minDistance;
            }
        }
    }
    
  • Todo
    
  • class Solution(object):
      def shortestWordDistance(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        ans = float("inf")
        idx1 = idx2 = -1
        for i in range(0, len(words)):
          word = words[i]
          if word in (word1, word2):
            if word == word1:
              idx1 = i
              if idx2 != -1 and idx1 != idx2:
                ans = min(ans, abs(idx2 - idx1))
            if word == word2:
              idx2 = i
              if idx1 != -1 and idx1 != idx2:
                ans = min(ans, abs(idx2 - idx1))
        return ans
    
    

All Problems

All Solutions