Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ef823d4

Browse files
Merge pull request SharingSource#323 from SharingSource/ac_oier
✨update: Modify 127
2 parents 283275c + 64bb3ff commit ef823d4

File tree

1 file changed

+23
-20
lines changed

1 file changed

+23
-20
lines changed

‎LeetCode/121-130/127. 单词接龙(困难).md‎

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -168,27 +168,30 @@ class Solution {
168168
// update 代表从 deque 中取出一个单词进行扩展,
169169
// cur 为当前方向的距离字典;other 为另外一个方向的距离字典
170170
int update(Deque<String> deque, Map<String, Integer> cur, Map<String, Integer> other) {
171-
// 获取当前需要扩展的原字符串
172-
String poll = deque.pollFirst();
173-
int n = poll.length();
171+
int m = deque.size();
172+
while (m-- > 0) {
173+
// 获取当前需要扩展的原字符串
174+
String poll = deque.pollFirst();
175+
int n = poll.length();
174176

175-
// 枚举替换原字符串的哪个字符 i
176-
for (int i = 0; i < n; i++) {
177-
// 枚举将 i 替换成哪个小写字母
178-
for (int j = 0; j < 26; j++) {
179-
// 替换后的字符串
180-
String sub = poll.substring(0, i) + String.valueOf((char)('a' + j)) + poll.substring(i + 1);
181-
if (set.contains(sub)) {
182-
// 如果该字符串在「当前方向」被记录过(拓展过),跳过即可
183-
if (cur.containsKey(sub)) continue;
184-
185-
// 如果该字符串在「另一方向」出现过,说明找到了联通两个方向的最短路
186-
if (other.containsKey(sub)) {
187-
return cur.get(poll) + 1 + other.get(sub);
188-
} else {
189-
// 否则加入 deque 队列
190-
deque.addLast(sub);
191-
cur.put(sub, cur.get(poll) + 1);
177+
// 枚举替换原字符串的哪个字符 i
178+
for (int i = 0; i < n; i++) {
179+
// 枚举将 i 替换成哪个小写字母
180+
for (int j = 0; j < 26; j++) {
181+
// 替换后的字符串
182+
String sub = poll.substring(0, i) + String.valueOf((char)('a' + j)) + poll.substring(i + 1);
183+
if (set.contains(sub)) {
184+
// 如果该字符串在「当前方向」被记录过(拓展过),跳过即可
185+
if (cur.containsKey(sub) && cur.get(sub) <= cur.get(poll) + 1) continue;
186+
187+
// 如果该字符串在「另一方向」出现过,说明找到了联通两个方向的最短路
188+
if (other.containsKey(sub)) {
189+
return cur.get(poll) + 1 + other.get(sub);
190+
} else {
191+
// 否则加入 deque 队列
192+
deque.addLast(sub);
193+
cur.put(sub, cur.get(poll) + 1);
194+
}
192195
}
193196
}
194197
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /