LeetCode Word Ladder解题报告

44 篇文章 0 订阅
43 篇文章 0 订阅
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.

题不难理解,输入的是:一个单词和一个字典,单词每次只允许改变一个字母变成字典中的某个单词,如此循环,判断是否能变成目标单词,如果能的话返回变换次数,否则返回0。

解题报告:
最直观的思路就是DFS,每次变成字典中的某个新单词,同时从字典中删除这个单词然后不断递归。
大数据时候超时。因为要求的是最短的变换次数,所以可以使用BFS,和DFS不一样不一次走到最深。逐层遍历变换了一次、二次、三次、n次的所有单词。
思考一下DFS和BFS的区别,举个最简单的例子,111 -> 311。
DFS的话,111->112,之后需要DFS 112的所有变形。同理111->113之后还要遍历113的所有变形。

而BFS的话,                      111
                     112  113 121 131  211  311

只需要6次就能找到最终结果。

实现方面的一个技巧是用2个队列,一个保存变形之后的单词,一个表示当前单词所经过的变换次数,两个对了保持同步。这样就能记录下来当前单词是经过了多少次变换得到的。
上AC代码:
public class Solution {
	public int ladderLength(String start, String end, HashSet<String> dict) 	{
            if(start.equals(end)==true||start==null||end==null) {
                return 0;
            }
            
            Queue queue = new LinkedList<String>();
            //记录当前节点所在的层数,也就是经过了多少次变换
            LinkedList<Integer> distanceQueue = new LinkedList<Integer>();
            queue.add(start);
            distanceQueue.add(1);
            int ret = 0;
            while(!queue.isEmpty()) {
                String str = (String)queue.poll();
                ret = (int)distanceQueue.poll();
                //对当前单词的每个字符逐个测试,生成的新单词是否存在于字典中
                for(int i=0; i<str.length(); i++){
                    char[] strCharArr = str.toCharArray();
                    for(char c='a'; c<='z'; c++){
                        strCharArr[i] = c;
                        String newWord = new String(strCharArr);
                        if(dict.contains(newWord)){
                            if(newWord.equals(end)) {
                                return ret + 1;
                            }
                            queue.add(newWord);
                            distanceQueue.add(ret + 1);
                            dict.remove(newWord);
                        }
                    }
                }
            }
            return 0;
        }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值