class Solution { public int ladderLength(String beginWord, String endWord, List<String> wordList) { Set<String> dict=new HashSet<String>(wordList); if(!dict.contains(endWord)) return 0; Set<String> set1=new HashSet<String>(Arrays.asList(beginWord)); Set<String> set2=new HashSet<String>(Arrays.asList(endWord)); return ladderLength(set1, set2, dict, 1); } private int ladderLength(Set<String> set1, Set<String> set2, Set<String> dict, int level) { if(set1.size()==0) return 0; if(set1.size()>set2.size()) return ladderLength(set2, set1, dict, level); dict.removeAll(set1); dict.removeAll(set2); Set<String> set3=new HashSet<String>(); for(String w:set1) for(int i=0;i<w.length();i++) { char[] arr=w.toCharArray(); for(char ch='a';ch<='z';ch++) { arr[i]=ch; String word=new String(arr); if(set2.contains(word)) return level+1; if(dict.contains(word)) set3.add(word); } } return ladderLength(set2, set3, dict, level+1); } }