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数组记录访问过的节点

还曾有另外一种想法:定义一个isWithinOne函数,判断两个String距离是否为1,但是可惜TLE了,主要是因为要挨个遍历dict里面每个元素,dict很大就过不了。不过思路还是很好的

 1 public class Solution {

 2     public int ladderLength(String start, String end, Set<String> dict) {

 3         LinkedList<String> queue = new LinkedList<String>();

 4         HashSet<String> isVisited = new HashSet<String>();

 5         queue.offer(start);

 6         isVisited.add(start);

 7         int PNum = 1;

 8         int CNum = 0;

 9         int level = 1;

10         while (!queue.isEmpty()) {

11             String cur = queue.poll();

12             PNum--;

13             if (isWithinOne(cur, end)) return level+1; 

14             for (String item : dict) {

15                 if (!isVisited.contains(item) && isWithinOne(cur, item)) {

16                     isVisited.add(item);

17                     queue.offer(item);

18                     CNum++;

19                 } 

20             }

21             if (PNum == 0) { // end with current level

22                 PNum = CNum;

23                 CNum = 0;

24                 level++;

25             }

26         }

27         return 0;

28     }

29     

30     public boolean isWithinOne(String cur, String end) {

31         int diff = 0;

32         for (int i=0; i<cur.length(); i++) {

33             if (cur.charAt(i) != end.charAt(i)) {

34                 diff++;

35             }

36         }

37         return diff==1? true : false;

38     }

39 }

 

你可能感兴趣的:(LeetCode)