Because of lots dups in dict, better to use hash set to filter it out.
class Solution { public int ladderLength(String beginWord, String endWord, List<String> wordList) { if (beginWord.length() == 0 || endWord.length() == 0 || beginWord.length() != endWord.length()) { return 0; } Set<String> dict = new HashSet<>(wordList); Queue<String> queue = new LinkedList<>(); int current = 1; int future = 0; int level = 1; queue.offer(beginWord); while (!queue.isEmpty()) { current--; String str = queue.poll(); for (int i = 0; i < beginWord.length(); i++) { StringBuilder sb = new StringBuilder(str); for (char c = 'a'; c <= 'z'; c++) { sb.replace(i, i + 1, String.valueOf(c)); String newStr = sb.toString(); if (dict.contains(newStr)) { if (newStr.equals(endWord)) { return level + 1; } dict.remove(newStr); queue.offer(newStr); future++; } } } if (current == 0) { current = future; future = 0;; level++; } } return 0; } }