问题
给定两个单词(开始和结束),在一个字典中,求从开始到结束的最短变换序列的长度,即:
每次只能更改一个字母每个中间单词必须存在于字典中,例如:
开始 = “hit”
结束 = “cog”
字典 = [“hot”,“dot”,“dog”,“lot”,“log”]。
因为一个最短的变换是“hit”->“hot”->“dot”->“dog”->“cog”,程序应该返回其长度为5。
注意:如果没有这样的转换序列,则返回0。所有的单词都有相同的长度。所有单词只包含小写字母字符。
这个问题是一个在面试中经常被问到的经典问题。
解决方案
1. 朴素方法
用最简单的方法,我们可以从开始的单词开始,每次改变一个字符,如果它在字典中,我们继续替换单词,直到开始 == 结束。
public static int ladderLength(String start, String end, HashSet<String> dict) {
int len = 0;
HashSet<String> visited = new HashSet<>();
for (int i = 0; i < start.length(); i++) {
char[] startArr = start.toCharArray();
for (char c = 'a'; c <= 'z'; c++) {
if (c == start.toCharArray()[i]) {
continue;
}
// 用a-z去替换
startArr[i] = c;
String temp = new String(startArr);
if (dict.contains(temp)) {
len++;
start = temp;
if (temp.equals(end)) {
return len;
}
}
}
}
return len;
}
显然,这还不够好,因为它找不到最优路径。
2. 广度优先搜索法
所以我们很快意识到这看起来像一个树搜索问题,广度优先搜索保证了最优解。
假设我们在字典中有一些单词,并且开始是“hit”,如下图所示:
我们可以使用两个队列来遍历树,一个存储节点,另一个存储步骤号。
public static int ladderLength2(String start, String end, HashSet<String> dict) {
if (dict.size() == 0) {
return 0;
}
dict.add(end);
LinkedList<String> wordQueue = new LinkedList<>();
LinkedList<Integer> distanceQueue = new LinkedList<>();
wordQueue.add(start);
distanceQueue.add(1);
int result = Integer.MAX_VALUE;
while (!wordQueue.isEmpty()) {
String currWord = wordQueue.pop();
Integer currDistance = distanceQueue.pop();
if (currWord.equals(end)) {
result = Math.min(result, currDistance);
}
for (int i = 0; i < currWord.length(); i++) {
char[] currCharArr = currWord.toCharArray();
for (char c = 'a'; c <= 'z'; c++) {
currCharArr[i] = c;
String newWord = new String(currCharArr);
// 如果字典中包含 只修改一个的字符 则入工作队列 并且距离+1 并在字典中排除
if (dict.contains(newWord)) {
wordQueue.add(newWord);
distanceQueue.add(currDistance + 1);
dict.remove(newWord);
}
}
}
}
if (result < Integer.MAX_VALUE) {
return result;
} else {
return 0;
}
}
我们能从这个问题学到什么?
- 使用广度或深度优先去解决问题。
- 使用两个队列,一个用于单词,另一个用于计数。