Skip to content

Commit 17c9079

Browse files
committed
fix127
1 parent 5514bcd commit 17c9079

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

leetCode-127-Word-Ladder.md

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,84 @@ private ArrayList<String> getNeighbors(String node, Set<String> dict) {
8383
}
8484
```
8585

86+
---
87+
88+
`2020.6.22` 更新,感谢 @cicada 指出,`leetcode` 增加了 `case` ,上边的代码不能 `AC` 了,我们需要考虑从第一个单词无法转到最后一个单词的情况,所以 `return` 前需要判断下。
89+
90+
```java
91+
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
92+
if (!wordList.contains(endWord)) {
93+
return 0;
94+
}
95+
int len = 0;
96+
Queue<String> queue = new LinkedList<>();
97+
queue.offer(beginWord);
98+
boolean isFound = false;
99+
Set<String> dict = new HashSet<>(wordList);
100+
Set<String> visited = new HashSet<>();
101+
visited.add(beginWord);
102+
while (!queue.isEmpty()) {
103+
int size = queue.size();
104+
Set<String> subVisited = new HashSet<>();
105+
for (int j = 0; j < size; j++) {
106+
String temp = queue.poll();
107+
// 一次性得到所有的下一个的节点
108+
ArrayList<String> neighbors = getNeighbors(temp, dict);
109+
for (String neighbor : neighbors) {
110+
if (!visited.contains(neighbor)) {
111+
subVisited.add(neighbor);
112+
//到达了结束单词,提前结束
113+
if (neighbor.equals(endWord)) {
114+
isFound = true;
115+
break;
116+
}
117+
queue.offer(neighbor);
118+
}
119+
}
120+
121+
}
122+
//当前层添加了元素,长度加一
123+
if (subVisited.size() > 0) {
124+
len++;
125+
}
126+
visited.addAll(subVisited);
127+
//找到以后,提前结束 while 循环,并且因为这里的层数从 0 计数,所以还需要加 1
128+
if (isFound) {
129+
len++;
130+
break;
131+
}
132+
}
133+
if(isFound){
134+
return len;
135+
}else{
136+
return 0;
137+
}
138+
139+
}
140+
141+
private ArrayList<String> getNeighbors(String node, Set<String> dict) {
142+
ArrayList<String> res = new ArrayList<String>();
143+
char chs[] = node.toCharArray();
144+
145+
for (char ch = 'a'; ch <= 'z'; ch++) {
146+
for (int i = 0; i < chs.length; i++) {
147+
if (chs[i] == ch)
148+
continue;
149+
char old_ch = chs[i];
150+
chs[i] = ch;
151+
if (dict.contains(String.valueOf(chs))) {
152+
res.add(String.valueOf(chs));
153+
}
154+
chs[i] = old_ch;
155+
}
156+
157+
}
158+
return res;
159+
}
160+
```
161+
162+
---
163+
86164
[126 题](<https://leetcode.wang/leetCode-126-Word-LadderII.html>) 中介绍了得到当前节点的相邻节点的两种方案,[官方题解](<https://leetcode.com/problems/word-ladder/solution/>) 中又提供了一种思路,虽然不容易想到,但蛮有意思,分享一下。
87165

88166
就是把所有的单词归类,具体的例子会好理解一些。

0 commit comments

Comments
 (0)