一开始自己以为是用dp来做,其实后来一想,这也不符合dp的3种常见类型。学习了答案才知,这是一道考图的经典题目,用的是bfs。
下面这张图真的很形象,解释了里面两个for循环是做什么的,同时一定要记得匹配了一个word后,要从字典中删除,这样来避免重复查找和死循环。
/**
* @param start, a string
* @param end, a string
* @param dict, a set of string
* @return an integer
*/
private class WordCount {
public String word;
public int count;
public WordCount (String word, int count) {
this.word = word;
this.count = count;
}
}
public int ladderLength(String start, String end, Set<String> dict) {
// write your code here
Queue<WordCount> queue = new LinkedList<>();
dict.add(end);
queue.offer(new WordCount(start, 1));
while (!queue.isEmpty()) {
WordCount wc = queue.poll();
if (wc.word.equals(end)) {
return wc.count;
}
String curS = wc.word;
for (int i = 0; i < curS.length(); i++) {
for (char c = 'a'; c <= 'z'; c++) {
char [] arrC = curS.toCharArray();
char temp = arrC[i];
arrC[i] = c;
String str = new String(arrC);
if (dict.contains(str)) {
queue.offer(new WordCount(str, wc.count + 1));
dict.remove(str);
}
arrC[i] = temp;
}
}
}
return 0;
}