0243. Shortest Word Distance

https://leetcode.com/problems/shortest-word-distance

Description

Given an array of strings wordsDict and two different strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list.

Example 1:

**Input:** wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
**Output:** 3

Example 2:

**Input:** wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
**Output:** 1

Constraints:

  • 1 <= wordsDict.length <= 3 * 104

  • 1 <= wordsDict[i].length <= 10

  • wordsDict[i] consists of lowercase English letters.

  • word1 and word2 are in wordsDict.

  • word1 != word2

ac

class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        int w1 = - words.length, w2 = - words.length;
        int diff = Integer.MAX_VALUE;
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word1)) {
                w1 = i;
                diff = Math.min(diff, Math.abs(w1 - w2));
            } else if (words[i].equals(word2)) {
                w2 = i;
                diff = Math.min(diff, Math.abs(w1 - w2));
            }
        }
        return diff;
    }
}

Last updated