Skip to content

Commit 311dd26

Browse files
format
1 parent 6494811 commit 311dd26

File tree

1 file changed

+12
-3
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+12
-3
lines changed

src/main/java/com/fishercoder/solutions/_127.java

+12-3
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,12 @@ public int ladderLength(String beginWord, String endWord, List<String> wordList)
4141
Set<String> startSet = new HashSet<>();
4242
Set<String> endSet = new HashSet<>();
4343
Set<String> visited = new HashSet<>();
44+
4445
startSet.add(beginWord);
45-
if (dict.contains(endWord)) endSet.add(endWord); // all transformed words must be in dict (including endWord)
46+
if (dict.contains(endWord)) {
47+
endSet.add(endWord); // all transformed words must be in dict (including endWord)
48+
}
49+
4650
for (int len = 2; !startSet.isEmpty(); len++) {
4751
Set<String> nq = new HashSet<>();
4852
for (String w : startSet) {
@@ -52,11 +56,16 @@ public int ladderLength(String beginWord, String endWord, List<String> wordList)
5256
if (c == w.charAt(j)) continue; // beginWord and endWord should not be the same
5357
ch[j] = c;
5458
String nb = String.valueOf(ch);
55-
if (endSet.contains(nb)) return len; // meet from two ends
56-
if (dict.contains(nb) && visited.add(nb)) nq.add(nb); // not meet yet, visited is safe to use
59+
if (endSet.contains(nb)) {
60+
return len; // meet from two ends
61+
}
62+
if (dict.contains(nb) && visited.add(nb)) {
63+
nq.add(nb); // not meet yet, visited is safe to use
64+
}
5765
}
5866
}
5967
}
68+
6069
startSet = (nq.size() < endSet.size()) ? nq : endSet; // switch to small one to traverse from other end
6170
endSet = (startSet == nq) ? endSet : nq;
6271
}

0 commit comments

Comments
 (0)