Skip to content

Commit 132fa92

Browse files
committed
https://leetcode.cn/problems/shortest-word-distance-iii/
1 parent 170f08b commit 132fa92

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ Step 2. Add the dependency
4545

4646
<summary>展开查看</summary>
4747

48+
https://leetcode.cn/problems/shortest-word-distance-iii/
49+
4850
https://leetcode.cn/problems/shortest-word-distance-ii/
4951

5052
https://leetcode.cn/problems/shortest-word-distance/

shortest-word-distance-iii/index.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
export default function shortestDistance(
2+
words: string[],
3+
word1: string,
4+
word2: string,
5+
): number {
6+
let posA = -1;
7+
let posB = -1;
8+
let minDistance = Infinity;
9+
10+
for (let i = 0; i < words.length; i++) {
11+
const word = words[i];
12+
13+
if (word === (word1)) {
14+
posA = i;
15+
} else if (word === (word2)) {
16+
posB = i; // this is covering normal cases, word1 not same as word2
17+
}
18+
19+
if (posA != -1 && posB != -1 && posA != posB) { // @note: update before reset posB
20+
minDistance = Math.min(minDistance, Math.abs(posA - posB));
21+
}
22+
23+
if (word1 === (word2)) {
24+
// always updating posA in above line, so after checking update posB
25+
// so that, posB is always the most recent word's index
26+
posB = posA;
27+
}
28+
}
29+
30+
return minDistance;
31+
}

shortest-word-distance-iii/test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { assertEquals } from "asserts";
2+
import shortestDistance from "./index.ts";
3+
4+
Deno.test("shortest-word-distance", () => {
5+
const words = ["practice", "makes", "perfect", "coding", "makes"];
6+
7+
const word1 = "coding",
8+
word2 = "makes";
9+
assertEquals(1, shortestDistance(words, word1, word2));
10+
});
11+
Deno.test("shortest-word-distance", () => {
12+
const words = ["practice", "makes", "perfect", "coding", "makes"];
13+
14+
const word1 = "makes", word2 = "makes";
15+
assertEquals(3, shortestDistance(words, word1, word2));
16+
});

0 commit comments

Comments
 (0)