Leetcode 127(Java)

来源:互联网 发布:nginx rtmp hls 编辑:程序博客网 时间:2024/05/20 03:06

虽然这道题目有些问题,但是的确帮助我加深了对BFS的理解。在网上看了许多解答以后自己写了答案,有什么可以改进或者考虑不周的地方希望指出。 一开始把单词想象成分散的结点,可以确定的是,beginWord是根结点,endWord是叶子结点,现在要通过其他分散的结点连一条最短路径将他们连接。即转化为树的最小层数问题,用广度优先是比较合理的。AC:

        public int ladderLength(String beginWord, String endWord, List<String> wordList) {            Queue<String> queue = new LinkedList<>();            //Integer代表了步骤数(树的深度)            HashMap<String,Integer> map = new HashMap<>();            //将beginword放入queue与map中            queue.offer(beginWord);            map.put(beginWord, 1);            while(queue!=null&&queue.size()!=0&&wordList.size()!=0){                String comparation = queue.poll();                StringBuilder str;                int length = comparation.length();                int level = map.get(comparation);                for(int i=0;i<length;i++){                    str = new StringBuilder(comparation);                    for(char ch='a';ch<='z';ch++){                            str.setCharAt(i, ch);                            String com = str.toString();                        if(com.equals(comparation)){                            continue;                        }                        if(com.equals(endWord)){                            return level+1;                        }                        if(wordList.contains(com)){                            queue.offer(com);                            wordList.remove(com);                            map.put(com, level+1);                        }                    }                }            }            return 0;        }
0 0
原创粉丝点击