Word Ladder

来源:互联网 发布:淘宝 作弊 编辑:程序博客网 时间:2024/06/01 17:23
public class Solution {    public int ladderLength(String beginWord, String endWord, Set<String> wordList) {        Queue<WordNode> queue = new LinkedList<>();        WordNode wnode = new WordNode(beginWord, 1);        queue.offer(wnode);        wordList.add(endWord);        while (!queue.isEmpty()) {            WordNode wn = queue.poll();            if (wn.word.equals(endWord)) {                return wn.steps;            }            String word = wn.word;            for (int i = 0; i < word.length(); i++) {                char[] chars = word.toCharArray();                for (char c = 'a'; c <= 'z'; c++) {                    chars[i] = c;                    String newWord = new String(chars);                    if (wordList.contains(newWord)) {                        WordNode newWn = new WordNode(newWord, wn.steps + 1);                        queue.offer(newWn);                        ///////////                        wordList.remove(newWord);                        ///////////                    }                }            }        }        return 0;    }        private class WordNode {        String word;        int steps;        public WordNode (String word, int steps) {            this.word = word;            this.steps = steps;        }    }}

0 0
原创粉丝点击