Word Ladder

Word Ladder 

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

  1. Only one letter can be changed at a time
  2. 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.

这道题A的略烦,按照提示,应该用BFS,确实用BFS思路比较清晰

参考:http://blog.csdn.net/yutianzuijin/article/details/12887747

百度和谷歌了一下,很多人都是直接贴代码,我也是经常这样干,不过上面这篇Blog还可以,照着他的思路我也写了一个BFS

主要思路

1.如果有为空的,或者两个相等直接返回0

2.使用队列,将start入队,遍历队列直到队列为空

2.1队列头部出队,head将head从第一个字母到最后一个字母分别用a~z进行替换,如果在dict中,没有被使用过,入队

2.2如果替换过后的单词和end也就是最后一个单词相等,直接返回到这个单词距离+1

还是文笔太烂~描述不清楚

 1 import java.util.HashMap;
 2 import java.util.LinkedList;
 3 import java.util.Queue;
 4 import java.util.Set;
 5 
 6 //class ListNode {
 7 //      public int val;
 8 //      public ListNode next;
 9 //      ListNode(int x) {
10 //          val = x;
11 //          next = null;
12 //      }
13 //  }
14 
15 public class Solution {
16     public int ladderLength(String start, String end, Set<String> dict) {
17         if(null == start || null == end || end.equals(start))
18             return 0;
19         if(hasOneWordDiff(start, end))                                            //如果两个只差一个字母返回距离为2
20             return 2;
21         //使用BFS,队列
22         //将开始的单词入队,直到对空为止
23         Queue<String> queue = new LinkedList<String>();                            //队列
24         //建议使用hashmap不用hashtable
25         HashMap<String, Integer> dist = new HashMap<String, Integer>();            //存放到单词的距离
26         queue.add(start);                                                        //将start元素放到队列中
27         dist.put(start, 1);                                                        //到start的距离为1
28         //开始BFS,直到队列为空
29         while(!queue.isEmpty()){
30             String head = queue.poll();                                            //队列头部出列
31             int distTemp = dist.get(head);                                        //start到单词的距离
32             //System.out.print(head + " " + distTemp);
33             
34             for(int i = 0; i < head.length(); i++){                                //从第一个字母开始替换,如果只有一个字母入队
35                 StringBuffer sb = new StringBuffer(head);
36                 for(char s = 'a'; s <= 'z'; s++){                                //每个字母替换成26个字母中的一个进行比较
37                     if(s == head.charAt(i))
38                         continue;
39                     sb.setCharAt(i, s);                                            //替换过后,只有一个字母不同,如果有这样的单词,入队
40                     
41                     if(sb.toString().equals(end)){                        
42                         return distTemp + 1;                                        
43                     }
44                     if(dict.contains(sb.toString()) && !dist.containsKey(sb.toString())){
45                         queue.add(sb.toString());                                //入队
46                         dist.put(sb.toString(), distTemp + 1);
47                     }
48                 }
49             }    
50         }
51         return 0;
52        
53     }
54     
55     /**
56      * 如果两个单词只有一个字母是不同的返回true,其他返回false
57      * @param str1
58      * @param str2
59      * @return
60      */
61     public boolean hasOneWordDiff(String str1, String str2){
62         int diff = 0;
63         for(int i = 0; i < str1.length(); i++){
64             if(str1.charAt(i) != str2.charAt(i)){
65                 diff++;
66                 if(diff >= 2)
67                     return false;                                //超过两个不同直接返回false
68             }
69         }
70         
71         return diff == 1;
72     }
73 }

 

posted on 2014-12-04 21:15  luckygxf  阅读(254)  评论(0编辑  收藏  举报

导航