2019.8.9 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)
这题实质上是一道图题,以每一个字符串和其在字典中的接龙字符串(只有一个字符不同的字符串)为一条无向边构建图,那么只需要依靠一个简单的BFS即可解决本题。
但是本题难在建图,难在如何高效地计算并存储每一条边的关系,如果单纯用三层循环来做会超时。这里可以将每一个字符串的所有模板(用*代替依次每一位)作为key,将所有符合模板的字符串作为value构建图,可以省去一层循环的复杂度。
传送门:单词接龙
Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则:
每次转换只能改变一个字母。
转换过程中的中间单词必须是字典中的单词。
说明:
如果不存在这样的转换序列,返回 0。
所有单词具有相同的长度。
所有单词只由小写字母组成。
字典中不存在重复的单词。
你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
示例1:
输入:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
输出: 5
解释: 一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",返回它的长度 5。
示例 2:
输入:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
输出:0
解释:endWord "cog" 不在字典中,所以无法进行转换。
import java.util.*;
/**
*
* Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
* Only one letter can be changed at a time.
* Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
* 给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则:
* 每次转换只能改变一个字母。
* 转换过程中的中间单词必须是字典中的单词。
*
*/
public class WordLadder {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
int len = beginWord.length();
//将字符替换模板“a*b”作为key,所有符合模板的字符串作为value创建哈希表,以此为边建立无向图
HashMap<String, ArrayList<String>> map = new HashMap<>();
for(String str : wordList){
for(int i = 0; i < len; i++){
String pattern = str.substring(0, i) + "*" + str.substring(i + 1, len);
map.putIfAbsent(pattern, new ArrayList<>());
map.get(pattern).add(str);
}
}
//对无向图进行BFS,利用HashSet保存已经遍历过的结点
HashSet<String> set = new HashSet<>();
LinkedList<String> list = new LinkedList<>();
list.add(beginWord);
int result = 1;
while(!list.isEmpty()){
int size = list.size();
for(int i = 0; i < size; i++){
String str = list.pollFirst();
if(str.equals(endWord)){
return result;
}
for(int j = 0; j < len; j++){
String pattern = str.substring(0, j) + "*" + str.substring(j + 1, len);
ArrayList<String> nextList = map.getOrDefault(pattern, new ArrayList<>());
for(String next : nextList){
if(!set.contains(next)){
list.add(next);
set.add(next);
}
}
}
}
result++;
}
return 0;
}
}
#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#