Word Ladder--思路一

Word Ladder leetcode java

题目

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence fromstart 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.

 

题解

 这道题是套用BFS同时也利用BFS能寻找最短路径的特性来解决问题。

 把每个单词作为一个node进行BFS。当取得当前字符串时,对他的每一位字符进行从a~z的替换,如果在字典里面,就入队,并将下层count++,并且为了避免环路,需把在字典里检测到的单词从字典里删除。这样对于当前字符串的每一位字符安装a~z替换后,在queue中的单词就作为下一层需要遍历的单词了。

 正因为BFS能够把一层所有可能性都遍历了,所以就保证了一旦找到一个单词equals(end),那么return的路径肯定是最短的。

 

 像给的例子 start = hit,end = cog,dict = [hot, dot, dog, lot, log]

 按照上述解题思路的走法就是:

  level = 1    hit   dict = [hot, dot, dog, lot, log]

         ait bit cit ... xit yit zit ,  hat hbt hct ... hot ... hxt hyt hzt ,  hia hib hic ... hix hiy hiz

 

  level = 2    hot  dict = [dot, dog, lot, log]

         aot bot cot dot ...  lot ... xot yot zot,hat hbt hct ... hxt hyt hzt,hoa hob hoc ... hox hoy hoz

 

  level = 3    dot lot  dict = [dog log]

         aot bot ... yot zot,dat dbt ...dyt dzt,doa dob ... dog .. doy doz,

         aot bot ... yot zot,lat lbt ... lyt lzt,loa lob ... log... loy loz

 

  level = 4   dog log dict = [] 

         aog bog cog

 

  level = 5   cog  dict = []

 

 代码如下:

 

复制代码
 1      public  int ladderLength(String start, String end, HashSet<String> dict) {
 2          if(start== null || end== null || start.length()==0 || end.length()==0 || start.length()!=end.length())  
 3          return 0; 
 4         
 5         LinkedList<String> wordQueue =  new LinkedList<String>();
 6          int level = 1;  // the start string already count for 1
 7           int curnum = 1; // the candidate num on current level
 8           int nextnum = 0; // counter for next level
 9          
10         wordQueue.add(start);
11         
12          while(!wordQueue.isEmpty()){
13             String word = wordQueue.poll();
14             curnum--;
15             
16              for( int i = 0; i < word.length(); i++){
17                  char[] wordunit = word.toCharArray();
18                  for( char j = 'a'; j <= 'z'; j++){
19                     wordunit[i] = j;
20                     String temp =  new String(wordunit);  
21                     
22                      if(temp.equals(end))
23                          return level+1;
24                      if(dict.contains(temp)){
25                         wordQueue.add(temp);
26                         nextnum++;
27                         dict.remove(temp);
28                     }
29                 }
30             }
31             
32              if(curnum == 0){
33                 curnum = nextnum;
34                 nextnum = 0;
35                 level++;
36             }
37         }
38         
39          return 0;
40     }
复制代码

                      


不用curnum和nextnum这两个变量去跟踪queue的大小与level的大小,让代码看起来更简洁一些。而且相对不容易出错。

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

if (start == null || end == null || start.length() == 0 || end.length() == 0 || start.length() != end.length())
return 0;

LinkedList<String> wordQueue = new LinkedList<String>();
int level = 1; //the start string already count for 1
wordQueue.add(start);

while (!wordQueue.isEmpty()) {

int size = wordQueue.size();

while (size > 0) {
String word = wordQueue.poll();
for (int i = 0; i < word.length(); i++) {
char[] wordunit = word.toCharArray();
for (char j = 'a'; j <= 'z'; j++) {
wordunit[i] = j;
String temp = new String(wordunit);

if (temp.equals(end))
return level + 1;
if (dict.contains(temp)) {
wordQueue.add(temp);
dict.remove(temp);
}
}
}
size--;
}
level++;
}
return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值