|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| -/**Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. |
| 3 | +/** |
| 4 | + * 243. Shortest Word Distance |
| 5 | + * |
| 6 | + * Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. |
4 | 7 |
|
5 | 8 | For example,
|
6 | 9 | Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
|
|
11 | 14 | Note:
|
12 | 15 | You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.*/
|
13 | 16 | public class _243 {
|
14 |
| - |
15 |
| - public int shortestDistance(String[] words, String word1, String word2) { |
16 |
| - |
17 |
| - int p = -1; |
18 |
| - int q = -1; |
19 |
| - int min = Integer.MAX_VALUE; |
20 |
| - for (int i = 0; i < words.length; i++) { |
21 |
| - if (words[i].equals(word1)) { |
22 |
| - p = i; |
23 |
| - } |
24 |
| - if (words[i].equals(word2)) { |
25 |
| - q = i; |
26 |
| - } |
27 |
| - if (p != -1 && q != -1) { |
28 |
| - min = Math.min(min, Math.abs(p - q)); |
| 17 | + public static class Solution1 { |
| 18 | + public int shortestDistance(String[] words, String word1, String word2) { |
| 19 | + int p = -1; |
| 20 | + int q = -1; |
| 21 | + int min = Integer.MAX_VALUE; |
| 22 | + for (int i = 0; i < words.length; i++) { |
| 23 | + if (words[i].equals(word1)) { |
| 24 | + p = i; |
| 25 | + } |
| 26 | + if (words[i].equals(word2)) { |
| 27 | + q = i; |
| 28 | + } |
| 29 | + if (p != -1 && q != -1) { |
| 30 | + min = Math.min(min, Math.abs(p - q)); |
| 31 | + } |
29 | 32 | }
|
30 |
| - } |
31 |
| - return min; |
| 33 | + return min; |
32 | 34 |
|
| 35 | + } |
33 | 36 | }
|
34 |
| - |
35 | 37 | }
|
0 commit comments