127. Word Ladder

Medium
注意,endWord必须在wordDict里面,startWord不需要。
加一个wordNode简直不要太有BFS的味道了,尤其要注意下面两行代码,防止了再次回到找过的词里面。

queue.offer(new wordNode(newString, curt.numSteps + 1));
set.remove(newString);

还得注意每次一个词换完所有位置的char后还是得换回来,因为我们每次只能换一个位置的字符。

class Solution {
    class wordNode{
        String word;
        int numSteps;
        public wordNode(String word, int numSteps){
            this.word = word;
            this.numSteps = numSteps;
        }
    }
    
    //"hit" -> hot -> dot -> lot -> log -> cog
    //"cog"
    //["hot","dot","dog","lot","log"]
    public int ladderLength(String beginWord, String endWord, List wordList) {
        if (!wordList.contains(endWord)){
            return 0;
        }
        Set set = new HashSet<>(wordList);
        set.add(endWord);
        Queue queue = new LinkedList<>();
        queue.offer(new wordNode(beginWord, 1));
        while (!queue.isEmpty()){
            wordNode curt = queue.poll();
            String word = curt.word;
            if (word.equals(endWord)){
                return curt.numSteps;
            }
            char[] chars = word.toCharArray();
            for (char c = 'a'; c <= 'z'; c++){
                for (int i = 0; i < chars.length; i++){
                    char temp = chars[i];
                    if (chars[i] != c){
                        chars[i] = c;
                    }
                    String newString = new String(chars);
                    if (set.contains(newString)){
                        queue.offer(new wordNode(newString, curt.numSteps + 1));
                        set.remove(newString);
                    }
                    chars[i] = temp;
                }
            }
        }
        return 0;
    }
}

你可能感兴趣的:(127. Word Ladder)