|
1 | 1 | packagecom.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | /**
|
| 4 | + * 245. Shortest Word Distance III |
| 5 | + * |
4 | 6 | * This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.
|
5 |
| -
|
6 |
| - Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. |
7 |
| -
|
8 |
| - word1 and word2 may be the same and they represent two individual words in the list. |
| 7 | + * Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. |
| 8 | + * word1 and word2 may be the same and they represent two individual words in the list. |
9 | 9 |
|
10 | 10 | For example,
|
11 | 11 | Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
|
|
18 | 18 | */
|
19 | 19 | publicclass_245 {
|
20 | 20 |
|
21 |
| -publicintshortestWordDistance(String[]words,Stringword1,Stringword2) { |
22 |
| -intp1 = -1; |
23 |
| -intp2 = -1; |
24 |
| -intmin =Integer.MAX_VALUE; |
25 |
| -for (inti =0;i <words.length;i++) { |
26 |
| -if (words[i].equals(word1)) { |
27 |
| -if (word1.equals(word2)) { |
28 |
| -if (p1 != -1 &&i -p1 <min) { |
29 |
| -min =i -p1; |
| 21 | +publicstaticclassSolution1 { |
| 22 | +publicintshortestWordDistance(String[]words,Stringword1,Stringword2) { |
| 23 | +intp1 = -1; |
| 24 | +intp2 = -1; |
| 25 | +intmin =Integer.MAX_VALUE; |
| 26 | +for (inti =0;i <words.length;i++) { |
| 27 | +if (words[i].equals(word1)) { |
| 28 | +if (word1.equals(word2)) { |
| 29 | +if (p1 != -1 &&i -p1 <min) { |
| 30 | +min =i -p1; |
| 31 | + } |
| 32 | +p1 =i; |
| 33 | + }else { |
| 34 | +p1 =i; |
| 35 | +if (p2 != -1 &&p1 -p2 <min) { |
| 36 | +min =p1 -p2; |
| 37 | + } |
30 | 38 | }
|
31 |
| -p1 =i; |
32 |
| - }else { |
33 |
| -p1 =i; |
34 |
| -if (p2 != -1 &&p1 -p2 <min) { |
35 |
| -min =p1 -p2; |
| 39 | + }elseif (words[i].equals(word2)) { |
| 40 | +p2 =i; |
| 41 | +if (p1 != -1 &&p2 -p1 <min) { |
| 42 | +min =p2 -p1; |
36 | 43 | }
|
37 | 44 | }
|
38 |
| - }elseif (words[i].equals(word2)) { |
39 |
| -p2 =i; |
40 |
| -if (p1 != -1 &&p2 -p1 <min) { |
41 |
| -min =p2 -p1; |
42 |
| - } |
43 | 45 | }
|
| 46 | +returnmin; |
44 | 47 | }
|
45 |
| -returnmin; |
46 | 48 | }
|
47 |
| - |
48 | 49 | }
|