[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;
    }
}

你可能感兴趣的:(leetcode)