Movatterモバイル変換


[0]ホーム

URL:


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

Commitb50aad3

Browse files
refactor 245
1 parent960e2dd commitb50aad3

File tree

1 file changed

+26
-25
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+26
-25
lines changed
Lines changed: 26 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
packagecom.fishercoder.solutions;
22

33
/**
4+
* 245. Shortest Word Distance III
5+
*
46
* 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.
99
1010
For example,
1111
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
@@ -18,31 +18,32 @@
1818
*/
1919
publicclass_245 {
2020

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+
}
3038
}
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;
3643
}
3744
}
38-
}elseif (words[i].equals(word2)) {
39-
p2 =i;
40-
if (p1 != -1 &&p2 -p1 <min) {
41-
min =p2 -p1;
42-
}
4345
}
46+
returnmin;
4447
}
45-
returnmin;
4648
}
47-
4849
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp