|
31 | 31 | */
|
32 | 32 |
|
33 | 33 | public class _127 {
|
| 34 | + public static class Solution1 { |
34 | 35 |
|
35 |
| - public int ladderLength(String beginWord, String endWord, List<String> wordList) { |
36 |
| - Set<String> beginSet = new HashSet<>(); |
37 |
| - Set<String> endSet = new HashSet<>(); |
38 |
| - Set<String> visited = new HashSet<>(); |
39 |
| - Set<String> dict = new HashSet<>(wordList); |
40 |
| - int len = 1; |
| 36 | + public int ladderLength(String beginWord, String endWord, List<String> wordList) { |
| 37 | + Set<String> beginSet = new HashSet<>(); |
| 38 | + Set<String> endSet = new HashSet<>(); |
| 39 | + Set<String> visited = new HashSet<>(); |
| 40 | + Set<String> dict = new HashSet<>(wordList); |
| 41 | + int len = 1; |
41 | 42 |
|
42 |
| - beginSet.add(beginWord); |
| 43 | + beginSet.add(beginWord); |
43 | 44 |
|
44 |
| - if (dict.contains(endWord)) { |
45 |
| - endSet.add(endWord); |
46 |
| - } |
| 45 | + if (dict.contains(endWord)) { |
| 46 | + endSet.add(endWord); |
| 47 | + } |
47 | 48 |
|
48 |
| - while (!beginSet.isEmpty() && !endSet.isEmpty()) { |
49 |
| - Set<String> nextBeginSet = new HashSet<>(); |
50 |
| - for (String word : beginSet) { |
51 |
| - char[] chars = word.toCharArray(); |
52 |
| - for (int i = 0; i < chars.length; i++) { |
53 |
| - for (char c = 'a'; c <= 'z'; c++) { |
54 |
| - char old = chars[i]; |
55 |
| - chars[i] = c; |
56 |
| - String newWord = new String(chars); |
57 |
| - if (endSet.contains(newWord)) { |
58 |
| - return len + 1; |
59 |
| - } |
| 49 | + while (!beginSet.isEmpty() && !endSet.isEmpty()) { |
| 50 | + Set<String> nextBeginSet = new HashSet<>(); |
| 51 | + for (String word : beginSet) { |
| 52 | + char[] chars = word.toCharArray(); |
| 53 | + for (int i = 0; i < chars.length; i++) { |
| 54 | + for (char c = 'a'; c <= 'z'; c++) { |
| 55 | + char old = chars[i]; |
| 56 | + chars[i] = c; |
| 57 | + String newWord = new String(chars); |
| 58 | + if (endSet.contains(newWord)) { |
| 59 | + return len + 1; |
| 60 | + } |
60 | 61 |
|
61 |
| - if (!visited.contains(newWord) && dict.contains(newWord)) { |
62 |
| - visited.add(newWord); |
63 |
| - nextBeginSet.add(newWord); |
| 62 | + if (!visited.contains(newWord) && dict.contains(newWord)) { |
| 63 | + visited.add(newWord); |
| 64 | + nextBeginSet.add(newWord); |
| 65 | + } |
| 66 | + chars[i] = old; |
64 | 67 | }
|
65 |
| - chars[i] = old; |
66 | 68 | }
|
67 | 69 | }
|
68 |
| - } |
69 | 70 |
|
70 |
| - beginSet = nextBeginSet; |
71 |
| - len++; |
| 71 | + beginSet = nextBeginSet; |
| 72 | + len++; |
| 73 | + } |
| 74 | + return 0; |
72 | 75 | }
|
73 |
| - return 0; |
74 | 76 | }
|
75 | 77 | }
|
0 commit comments