Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit ea7c0cd

Browse files
committed
Add solution #244
1 parent 1989e55 commit ea7c0cd

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@
233233
241|[Different Ways to Add Parentheses](./solutions/0241-different-ways-to-add-parentheses.js)|Medium|
234234
242|[Valid Anagram](./solutions/0242-valid-anagram.js)|Easy|
235235
243|[Shortest Word Distance](./solutions/0243-shortest-word-distance.js)|Easy|
236+
244|[Shortest Word Distance II](./solutions/0244-shortest-word-distance-ii.js)|Medium|
236237
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
237238
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
238239
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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

Comments
 (0)