Skip to content

Commit 8dff54d

Browse files
[N-0] refactor 127
1 parent 79a104e commit 8dff54d

File tree

1 file changed

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

1 file changed

+4
-12
lines changed

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

+4-12
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@
77
/**
88
* 127. Word Ladder
99
*
10-
* Given two words (beginWord and endWord),
11-
* and a dictionary's word list,
10+
* Given two words (beginWord and endWord), and a dictionary's word list,
1211
* find the length of shortest transformation sequence from beginWord to endWord, such that:
1312
* Only one letter can be changed at a time.
1413
* Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
@@ -33,7 +32,6 @@
3332

3433
public class _127 {
3534

36-
/**We can share a visited set from both ends since we cannot remove word from dict.*/
3735
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
3836
Set<String> beginSet = new HashSet<>();
3937
Set<String> endSet = new HashSet<>();
@@ -48,13 +46,7 @@ public int ladderLength(String beginWord, String endWord, List<String> wordList)
4846
}
4947

5048
while (!beginSet.isEmpty() && !endSet.isEmpty()) {
51-
if (beginSet.size() > endSet.size()) {
52-
Set<String> temp = beginSet;
53-
beginSet = endSet;
54-
endSet = temp;
55-
}
56-
57-
Set<String> temp = new HashSet<>();
49+
Set<String> nextBeginSet = new HashSet<>();
5850
for (String word : beginSet) {
5951
char[] chars = word.toCharArray();
6052
for (int i = 0; i < chars.length; i++) {
@@ -68,14 +60,14 @@ public int ladderLength(String beginWord, String endWord, List<String> wordList)
6860

6961
if (!visited.contains(newWord) && dict.contains(newWord)) {
7062
visited.add(newWord);
71-
temp.add(newWord);
63+
nextBeginSet.add(newWord);
7264
}
7365
chars[i] = old;
7466
}
7567
}
7668
}
7769

78-
beginSet = temp;
70+
beginSet = nextBeginSet;
7971
len++;
8072
}
8173
return 0;

0 commit comments

Comments
 (0)