Word Ladder 07/30
Example
public class Solution {
/*
* @param start: a string
* @param end: a string
* @param dict: a set of string
* @return: An integer
*/
public int ladderLength(String start, String end, Set<String> dict) {
if(start.equals(end)){
return 1;
}
if(dict.size() == 0){
return 0;
}
Queue<String> queue = new LinkedList<>();
dict.add(end);
queue.offer(start);
int change = 0;
while(!queue.isEmpty()){
int size = queue.size();
change++;
for (int i = 0; i < size ;i++ ){
String word = queue.poll();
if(word.equals(end)){
return change;
}
List<String> list = findNext(word,dict);
for(String s : list){
if(s.equals(end)){
return change+1;
}
queue.offer(s);
}
}
}
return change;
}
public List<String> findNext(String s, Set<String> dict){
int diff = 0;
List<String> res = new ArrayList<>();
for(String word : dict){
for(int i = 0; i < s.length();i++){
if(s.charAt(i) == word.charAt(i)){
continue;
}
diff++;
}
if(diff == 1){
res.add(word);
}
diff= 0;
}
dict.removeAll(res);
return res;
}
}Last updated