public int ladderLength(String start, String end, Set dict) { if (start.length() != end.length()) { return 0; } if (dict == null || dict.size() == 0) { return 0; } Queue wordQueue = new LinkedList(); Queue distanceQueue = new LinkedList(); wordQueue.add(start); distanceQueue.add(1); while (!wordQueue.isEmpty()) { String curWord = wordQueue.poll(); Integer curDistance = distanceQueue.poll(); if (curWord.equals(end)) { return curDistance; } for (int i = 0; i < curWord.length(); i++) { char[] chars = curWord.toCharArray(); //watch out! here is char for a to z!!! for (char c = 'a'; c <= 'z'; c++) { chars[i] = c; String newWord = new String(chars); if (dict.contains(newWord)) { wordQueue.add(newWord); distanceQueue.add(curDistance + 1); dict.remove(newWord); } } } } return 0; }