Leetcode: Word Ladder

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.

难度:96.这道题看似一个关于字符串操作的题目,其实要解决这个问题得用图的方法。我们先给题目进行图的映射,顶点则是每个字符串,然后两个字符串如果相差一个字符则我们进行连边。接下来看看这个方法的优势,注意到我们的字符集只有小写字母,而且字符串长度固定,假设是L。那么可以注意到每一个字符可以对应的边则有25个(26个小写字母减去自己),那么一个字符串可能存在的边是25*L条。接下来就是检测这些边对应的字符串是否在字典里,就可以得到一个完整的图的结构了。根据题目的要求,等价于求这个图一个顶点到另一个顶点的最短路径,一般我们用广度优先搜索。这里因为需要确定level数作为最短路径跳数,所以类似Binary Tree Level Order Traversal那样记录了上下两层节点数ParentNum 和ChildNum

注意19行字符串转换为String最好用 String st = new String(current); 使用 String st = current.toString(); 要出错

而长度为L的字符串总共有26^L,所以时间复杂度是O(min(26^L, size(dict)),空间上需要存储访问情况,也是O(min(26^L, size(dict))。

 1 public class Solution {
 2     public int ladderLength(String start, String end, Set<String> dict) {
 3         if (start==null || end==null || start.length()==0 || end.length()==0 || start.length()!=end.length())
 4             return 0;
 5         HashSet<String> visited = new HashSet<String>();
 6         LinkedList<String> queue = new LinkedList<String>();
 7         queue.add(start);
 8         visited.add(start);
 9         int parentNum = 1;
10         int childNum = 0;
11         int level = 1;
12         while (!queue.isEmpty()) {
13             String cur = queue.poll();
14             parentNum--;
15             for (int i=0; i<cur.length(); i++) {
16                 char[] current = cur.toCharArray();
17                 for (char c='a'; c<='z'; c++) {
18                     current[i] = c;
19                     String st = new String(current);
20                     if (st.equals(end)) {
21                         return level+1;
22                     }
23                     if (dict.contains(st) && !visited.contains(st)) {
24                         queue.add(st);
25                         visited.add(st);
26                         childNum++;
27                     }
28                 }
29             }
30             if (parentNum == 0) {
31                 parentNum = childNum;
32                 childNum = 0;
33                 level++;
34             }
35         }
36         return 0;
37     }
38 }

 作者道题还是有很多心得体会的,比如String是immutable的,如何改动其中一个元素?上面代码16行提供了一个非常好的方法,那就是先把String转化为CharArray, 改了元素之后再转回String,注意CharArray转String是new String(array). 另一种办法就是用StringBuffer的setCharAt()

写DFS, BFS不要忘了定义一个isVisited数组记录访问过的节点

别人的写法,不用visited数组,这样写比较好

 1 public class Solution {
 2 
 3     public int ladderLength(String beginWord, String endWord, Set<String> wordDict) {
 4         Queue<String> queue = new LinkedList<String>();
 5         // step用来记录跳数
 6         int step = 2;
 7         queue.offer(beginWord);
 8         while(!queue.isEmpty()){
 9             int size = queue.size();
10             // 控制size来确保一次while循环只计算同一层的节点,有点像二叉树level order遍历
11             for(int j = 0; j < size; j++){
12                String currWord = queue.poll();
13                 // 循环这个词从第一位字母到最后一位字母
14                 for(int i = 0; i < endWord.length(); i++){
15                     // 循环这一位被替换成25个其他字母的情况
16                     for(char letter = 'a'; letter <= 'z'; letter++){
17                         StringBuilder newWord = new StringBuilder(currWord);
18                         newWord.setCharAt(i, letter);
19                         if(endWord.equals(newWord.toString())){
20                             return step;    
21                         } else if(wordDict.contains(newWord.toString())){
22                             wordDict.remove(newWord.toString());
23                             queue.offer(newWord.toString());
24                         }
25                     }
26                 } 
27             }
28             step++;
29         }
30         return 0;
31     }
32 }

 感觉如果要找出所有路径的话,是不是还是要用DFS backtracking的思路了?BFS想了一下不是很好写

原文地址:https://www.cnblogs.com/EdwardLiu/p/4018214.html