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 01f0fa7

Browse files
单词接龙 BFS
1 parent a48449c commit 01f0fa7

File tree

1 file changed

+27
-30
lines changed

1 file changed

+27
-30
lines changed

‎127.单词接龙.java‎

Lines changed: 27 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -61,49 +61,46 @@ public int ladderLength(String beginWord, String endWord, List<String> wordList)
6161
if (!wordList.contains(endWord)) {
6262
return 0;
6363
}
64-
Set<String> dict = new HashSet<>(wordList);
65-
Set<String> upper = new HashSet<>();
6664
Queue<String> queue = new LinkedList<>();
67-
queue.offer(beginWord);
68-
int length = 0;
65+
queue.add(endWord);
66+
int step = 0;
6967
while (!queue.isEmpty()) {
70-
length++;
7168
int size = queue.size();
72-
Set<String> curLevel = newHashSet<>();
69+
step++;
7370
for (int i = 0; i < size; i++) {
74-
String curWord = queue.poll();
75-
List<String> allNext = getAllNext(curWord, dict);
76-
for (String word : allNext) {
77-
if (!upper.contains(word)) {
78-
curLevel.add(word);
79-
queue.offer(word);
80-
if (endWord.equals(word)) {
81-
return length + 1;
82-
}
71+
String target = queue.poll();
72+
if (isNext(target, beginWord)) {
73+
return step + 1;
74+
}
75+
for (String word : wordList) {
76+
if (word.equals(target)) {
77+
continue;
78+
}
79+
if (isNext(word, target)) {
80+
queue.add(word);
8381
}
8482
}
8583
}
86-
upper.addAll(curLevel);
84+
wordList.removeAll(queue);
8785
}
8886
return 0;
8987
}
9088

91-
private List<String> getAllNext(String word, Set<String> wordList) {
92-
List<String> list = newArrayList<>();
93-
for (int i = 0;i < word.length(); i++) {
94-
char[] chars = word.toCharArray();
95-
charorigin = chars[i];
96-
for (charc = 'a'; c <= 'z'; c++) {
97-
if (origin != c) {
98-
chars[i] = c;
99-
Strings = newString(chars);
100-
if (wordList.contains(s)) {
101-
list.add(s);
102-
}
89+
private booleanisNext(String a, Stringb) {
90+
intl = a.length();
91+
int flag = 0;
92+
for (inti = 0; i < l; i++) {
93+
if (a.charAt(i) == b.charAt(i)) {
94+
continue;
95+
}
96+
if (a.charAt(i) != b.charAt(i)) {
97+
if (flag == 0) {
98+
flag = 1;
99+
} else {
100+
returnfalse;
103101
}
104102
}
105103
}
106-
return list;
104+
return true;
107105
}
108106
}
109-

0 commit comments

Comments
(0)

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