diff --git a/problems/kamacoder/0110.字符串接龙.md b/problems/kamacoder/0110.字符串接龙.md index 5a60dbb7..feeec6dd 100644 --- a/problems/kamacoder/0110.字符串接龙.md +++ b/problems/kamacoder/0110.字符串接龙.md @@ -153,6 +153,68 @@ int main() { ## 其他语言版本 ### Java +```Java +public class Main { + // BFS方法 + public static int ladderLength(String beginWord, String endWord, List wordList) { + // 使用set作为查询容器,效率更高 + HashSet set = new HashSet<>(wordList); + + // 声明一个queue存储每次变更一个字符得到的且存在于容器中的新字符串 + Queue queue = new LinkedList<>(); + + // 声明一个hashMap存储遍历到的字符串以及所走过的路径path + HashMap visitMap = new HashMap<>(); + queue.offer(beginWord); + visitMap.put(beginWord, 1); + + while (!queue.isEmpty()) { + String curWord = queue.poll(); + int path = visitMap.get(curWord); + + for (int i = 0; i < curWord.length(); i++) { + char[] ch = curWord.toCharArray(); + // 每个位置尝试26个字母 + for (char k = 'a'; k <= 'z'; k++) { + ch[i] = k; + + String newWord = new String(ch); + if (newWord.equals(endWord)) return path + 1; + + // 如果这个新字符串存在于容器且之前未被访问到 + if (set.contains(newWord) && !visitMap.containsKey(newWord)) { + visitMap.put(newWord, path + 1); + queue.offer(newWord); + } + } + } + } + + return 0; + } + + public static void main (String[] args) { + /* code */ + // 接收输入 + Scanner sc = new Scanner(System.in); + int N = sc.nextInt(); + sc.nextLine(); + String[] strs = sc.nextLine().split(" "); + + List wordList = new ArrayList<>(); + for (int i = 0; i < N; i++) { + wordList.add(sc.nextLine()); + } + + // wordList.add(strs[1]); + + // 打印结果 + int result = ladderLength(strs[0], strs[1], wordList); + System.out.println(result); + } +} + +``` ### Python