Skip to content

Commit ef99b46

Browse files
author
Your Name
committed
更新 0110.字符串接龙 BFS解法Java版
1 parent 0ed1eb3 commit ef99b46

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

problems/kamacoder/0110.字符串接龙.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,68 @@ int main() {
153153
## 其他语言版本
154154

155155
### Java
156+
```Java
157+
public class Main {
158+
// BFS方法
159+
public static int ladderLength(String beginWord, String endWord, List<String> wordList) {
160+
// 使用set作为查询容器,效率更高
161+
HashSet<String> set = new HashSet<>(wordList);
162+
163+
// 声明一个queue存储每次变更一个字符得到的且存在于容器中的新字符串
164+
Queue<String> queue = new LinkedList<>();
165+
166+
// 声明一个hashMap存储遍历到的字符串以及所走过的路径path
167+
HashMap<String, Integer> visitMap = new HashMap<>();
168+
queue.offer(beginWord);
169+
visitMap.put(beginWord, 1);
170+
171+
while (!queue.isEmpty()) {
172+
String curWord = queue.poll();
173+
int path = visitMap.get(curWord);
174+
175+
for (int i = 0; i < curWord.length(); i++) {
176+
char[] ch = curWord.toCharArray();
177+
// 每个位置尝试26个字母
178+
for (char k = 'a'; k <= 'z'; k++) {
179+
ch[i] = k;
180+
181+
String newWord = new String(ch);
182+
if (newWord.equals(endWord)) return path + 1;
183+
184+
// 如果这个新字符串存在于容器且之前未被访问到
185+
if (set.contains(newWord) && !visitMap.containsKey(newWord)) {
186+
visitMap.put(newWord, path + 1);
187+
queue.offer(newWord);
188+
}
189+
}
190+
}
191+
}
192+
193+
return 0;
194+
}
195+
196+
public static void main (String[] args) {
197+
/* code */
198+
// 接收输入
199+
Scanner sc = new Scanner(System.in);
200+
int N = sc.nextInt();
201+
sc.nextLine();
202+
String[] strs = sc.nextLine().split(" ");
203+
204+
List<String> wordList = new ArrayList<>();
205+
for (int i = 0; i < N; i++) {
206+
wordList.add(sc.nextLine());
207+
}
208+
209+
// wordList.add(strs[1]);
210+
211+
// 打印结果
212+
int result = ladderLength(strs[0], strs[1], wordList);
213+
System.out.println(result);
214+
}
215+
}
216+
217+
```
156218

157219
### Python
158220

0 commit comments

Comments
 (0)