Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
bug code
1 public class Solution { 2 public int ladderLength(String start, String end, HashSet<String> dict) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 if(dict.size() == 0 || start.equals(end)){ 6 return 0; 7 } 8 //dict.add(start); 9 dict.remove(start); 10 dict.add(end); 11 int result = getLen(start, end, dict, 0); 12 if(result == 0){ 13 return result; 14 } 15 return result + 1; 16 } 17 18 public int getLen(String start, String end, HashSet<String> dict, int len){ 19 if(start.equals(end)){ 20 return len; 21 } 22 23 HashSet<String> neighbors = getNeighbors(start, dict); 24 int maxLen = len; 25 for(String n : neighbors){ 26 dict.remove(n); 27 int tmp = getLen(n, end, dict, len + 1); 28 if(tmp > maxLen){ 29 maxLen = tmp; 30 } 31 dict.add(n); 32 } 33 return maxLen; 34 } 35 36 public HashSet<String> getNeighbors(String start, HashSet<String> dict){ 37 HashSet<String> result = new HashSet<String>(); 38 for(int i = 0; i < start.length(); i++){ 39 StringBuffer sb = new StringBuffer(); 40 if(i == 1){ 41 sb.append(start.substring(0, 1)); 42 } else if(i == 0){ 43 44 } else { 45 sb.append(start.substring(0, i)); 46 } 47 for(char c = 'a'; c <= 'z'; c++){ 48 if(c != start.charAt(i)){ 49 sb.append(c).append(start.substring(i + 1)); 50 if(dict.contains(sb.toString())){ 51 result.add(sb.toString()); 52 } 53 } 54 } 55 } 56 return result; 57 } 58 }