|
1 | 1 | packagecom.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 | publicclass_243 {
|
14 |
| - |
15 |
| -publicintshortestDistance(String[]words,Stringword1,Stringword2) { |
16 |
| - |
17 |
| -intp = -1; |
18 |
| -intq =-1; |
19 |
| -intmin =Integer.MAX_VALUE; |
20 |
| -for (inti =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 | +publicstaticclassSolution1 { |
| 18 | +publicintshortestDistance(String[]words,Stringword1,Stringword2) { |
| 19 | +intp = -1; |
| 20 | +intq = -1; |
| 21 | +intmin =Integer.MAX_VALUE; |
| 22 | +for (inti =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 |
| -returnmin; |
| 33 | +returnmin; |
32 | 34 |
|
| 35 | + } |
33 | 36 | }
|
34 |
| - |
35 | 37 | }
|