|
| 1 | +/** |
| 2 | + * 244. Shortest Word Distance II |
| 3 | + * https://leetcode.com/problems/shortest-word-distance-ii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Design a data structure that will be initialized with a string array, and then it should |
| 7 | + * answer queries of the shortest distance between two different strings from the array. |
| 8 | + * |
| 9 | + * Implement the WordDistance class: |
| 10 | + * - WordDistance(String[] wordsDict) initializes the object with the strings array wordsDict. |
| 11 | + * - int shortest(String word1, String word2) returns the shortest distance between word1 and |
| 12 | + * word2 in the array wordsDict. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {string[]} wordsDict |
| 17 | + */ |
| 18 | +var WordDistance = function(wordsDict) { |
| 19 | + this.wordIndices = new Map(); |
| 20 | + for (let i = 0; i < wordsDict.length; i++) { |
| 21 | + if (!this.wordIndices.has(wordsDict[i])) { |
| 22 | + this.wordIndices.set(wordsDict[i], []); |
| 23 | + } |
| 24 | + this.wordIndices.get(wordsDict[i]).push(i); |
| 25 | + } |
| 26 | +}; |
| 27 | + |
| 28 | +/** |
| 29 | + * @param {string} word1 |
| 30 | + * @param {string} word2 |
| 31 | + * @return {number} |
| 32 | + */ |
| 33 | +WordDistance.prototype.shortest = function(word1, word2) { |
| 34 | + const indices1 = this.wordIndices.get(word1); |
| 35 | + const indices2 = this.wordIndices.get(word2); |
| 36 | + let minDistance = Infinity; |
| 37 | + let i = 0; |
| 38 | + let j = 0; |
| 39 | + |
| 40 | + while (i < indices1.length && j < indices2.length) { |
| 41 | + minDistance = Math.min(minDistance, Math.abs(indices1[i] - indices2[j])); |
| 42 | + if (indices1[i] < indices2[j]) { |
| 43 | + i++; |
| 44 | + } else { |
| 45 | + j++; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + return minDistance; |
| 50 | +}; |
0 commit comments