[leetcode-127]Word Ladder(java)

问题如下:
Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, 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.

分析:想了好久没有一个特别明显的思路,在网上看到BFS的字样,瞬间就开朗了,的确,这道题就是一个搜索问题,搜索问题可以用BFS和DFS来进行。对于这道题而言,我们相当于是找字典树的最小深度,而这样的话,用BFS是最合适不过的。
然后还有一个小trick,就是注意在添加到队列之后,马上从字典中将该元素删除,为啥要这样,防止对同一元素重复添加。

代码如下:612ms

public class Solution {
    public int ladderLength(String beginWord, String endWord, Set<String> wordDict) {
        Queue<String> queue = new LinkedList<>();
        queue.offer(beginWord);
        HashMap<String,Integer> maps = new HashMap<>();
        maps.put(beginWord,1);
        if(wordDict.contains(beginWord))
            wordDict.remove(beginWord);

        while(!queue.isEmpty()){
            String top = queue.poll();
            int length = top.length();
            StringBuilder builder;

            int level = maps.get(top);
            for(int i = 0;i<length;i++){
                builder = new StringBuilder(top);
                for(char c = 'a';c<='z';c++){
                    builder.setCharAt(i,c);
                    String tmpStr = builder.toString();
                    if(tmpStr.equals(top))
                        continue;
                    if(tmpStr.equals(endWord)){
                        return level+1;
                    }
                    if(wordDict.contains(tmpStr)){
                        queue.offer(tmpStr);
                        wordDict.remove(tmpStr);
                        maps.put(tmpStr,level+1);
                    }
                }
            }
        }
        return 0;
    }
}
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值