File tree 2 files changed +23
-1
lines changed
2 files changed +23
-1
lines changed Original file line number Diff line number Diff line change 212
212
| 240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii) | [](src/SearchA2DMatrixII.java) | |
213
213
| 241 | [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses) | | |
214
214
| 242 | [Valid Anagram](https://leetcode.com/problems/valid-anagram) | [](src/ValidAnagram.java) [](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) | [](src/ShortestWordDistance.java) | |
216
216
| 244 | 🔒 [Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii) | | |
217
217
| 245 | 🔒 [Shortest Word Distance III](https://leetcode.com/problems/shortest-word-distance-iii) | | |
218
218
| 246 | 🔒 [Strobogramatic Number](https://leetcode.com/problems/strobogrammatic-number) | | |
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments