文章目录
思路
解题方法
复杂度
时间复杂度:
空间复杂度:
Code
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
// 总词汇表
Set<String> dict = new HashSet<>(wordList);
if (!dict.contains(endWord)) {
return 0;
}
// 数据量小的一侧
Set<String> smallLevel = new HashSet<>();
// 数据量大的一侧
Set<String> bigLevel = new HashSet<>();
// 数据量小的下一侧
Set<String> nextLevel = new HashSet<>();
smallLevel.add(beginWord);
bigLevel.add(endWord);
for (int len = 2; !smallLevel.isEmpty(); len++) {
for (String w : smallLevel) {
// 从小的一侧拓展
char[] word = w.toCharArray();
for (int j = 0; j < word.length; j++) {
char old = word[j];
for (char change = 'a'; change <= 'z'; change++) {
if (change != old) {
word[j] = change;
String next = String.valueOf(word);
if (bigLevel.contains(next)) {
return len;
}
if (dict.contains(next)) {
dict.remove(next);
nextLevel.add(next);
}
}
}
word[j] = old;
}
}
if (nextLevel.size() <= bigLevel.size()) {
// 交换当前层和较小层
Set<String> temp = smallLevel;
smallLevel = nextLevel;
nextLevel = temp;
} else {
// 当前层大于较大层 交换当前层和较大层 较大层和较小层
Set<String> temp = smallLevel;
smallLevel = bigLevel;
bigLevel = nextLevel;
nextLevel = temp;
}
nextLevel.clear();
}
return 0;
}
}