7
7
/**
8
8
* 127. Word Ladder
9
9
*
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,
12
11
* find the length of shortest transformation sequence from beginWord to endWord, such that:
13
12
* Only one letter can be changed at a time.
14
13
* Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
33
32
34
33
public class _127 {
35
34
36
- /**We can share a visited set from both ends since we cannot remove word from dict.*/
37
35
public int ladderLength (String beginWord , String endWord , List <String > wordList ) {
38
36
Set <String > beginSet = new HashSet <>();
39
37
Set <String > endSet = new HashSet <>();
@@ -48,13 +46,7 @@ public int ladderLength(String beginWord, String endWord, List<String> wordList)
48
46
}
49
47
50
48
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 <>();
58
50
for (String word : beginSet ) {
59
51
char [] chars = word .toCharArray ();
60
52
for (int i = 0 ; i < chars .length ; i ++) {
@@ -68,14 +60,14 @@ public int ladderLength(String beginWord, String endWord, List<String> wordList)
68
60
69
61
if (!visited .contains (newWord ) && dict .contains (newWord )) {
70
62
visited .add (newWord );
71
- temp .add (newWord );
63
+ nextBeginSet .add (newWord );
72
64
}
73
65
chars [i ] = old ;
74
66
}
75
67
}
76
68
}
77
69
78
- beginSet = temp ;
70
+ beginSet = nextBeginSet ;
79
71
len ++;
80
72
}
81
73
return 0 ;
0 commit comments