publicintladderLength(String beginWord, String endWord, List<String> wordList){ if (!wordList.contains(endWord)) { return0; } Set<String> wordSet = new HashSet<>(wordList); Queue<String> queue = new LinkedList<>(); queue.offer(beginWord); int len = beginWord.length(); int step = 0;
while (!queue.isEmpty()) { ++step; // 对上一轮压进的所有值进行处理 for (int size = queue.size(); size > 0; size--) { String word = queue.poll(); // 针对String,获得其更改一位且在wordSet存在的值 for (int i = 0; i < len; i++) { for (char j = 'a'; j < 'z'; j++) { char[] arr = word.toCharArray(); arr[i] = j; String tempWord = new String(arr); if (endWord.equals(tempWord)) { return step + 1; } if (!wordSet.contains(tempWord)) { continue; } wordSet.remove(tempWord); queue.offer(tempWord); } } } } return0; }