Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b4f3197

Browse files
solves #243: Shortest Word Distance
1 parent 2cb17d0 commit b4f3197

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

β€ŽREADME.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@
212212
| 240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii) | [![Java](assets/java.png)](src/SearchA2DMatrixII.java) | |
213213
| 241 | [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses) | | |
214214
| 242 | [Valid Anagram](https://leetcode.com/problems/valid-anagram) | [![Java](assets/java.png)](src/ValidAnagram.java) [![Python](assets/python.png)](python/delete_node_in_linked_list.py) | |
215-
| 243 | πŸ”’ [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance) | | |
215+
| 243 | πŸ”’ [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance) | [![Java](assets/java.png)](src/ShortestWordDistance.java) | |
216216
| 244 | πŸ”’ [Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii) | | |
217217
| 245 | πŸ”’ [Shortest Word Distance III](https://leetcode.com/problems/shortest-word-distance-iii) | | |
218218
| 246 | πŸ”’ [Strobogramatic Number](https://leetcode.com/problems/strobogrammatic-number) | | |

β€Žsrc/ShortestWordDistance.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// https://leetcode.com/problems/shortest-word-distance
2+
// N: number of words, M: average word length
3+
// T: O(N * M)
4+
// S: O(1)
5+
6+
public class ShortestWordDistance {
7+
public int shortestDistance(String[] wordsDict, String word1, String word2) {
8+
int result = wordsDict.length, i = -1, j = -1;
9+
for (int index = 0 ; index < wordsDict.length ; index++) {
10+
if (wordsDict[index].equals(word1)) {
11+
i = index;
12+
} else if (wordsDict[index].equals(word2)) {
13+
j = index;
14+
}
15+
16+
if (i != -1 && j != -1) {
17+
result = Math.min(result, Math.abs(j - i));
18+
}
19+
}
20+
return result;
21+
}
22+
}

0 commit comments

Comments
(0)

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /