[Leetcode] Word Ladder

来源:互联网 发布:golang cobra 编辑:程序博客网 时间:2024/06/05 09:03

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the word list

For example,

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.

  • All words contain only lowercase alphabetic characters.
BFS。一开始一直报Timeout,原因是原代码遍历了wordList,然后检查word和现有的word是否diff <= 1,当wordList巨大时开销很大。现在将word每个位置上的char都从a到z的代入,虽然依旧开销很大,但是当wordList很大时反而更有效率。

public class Solution {    public int ladderLength(String beginWord, String endWord, Set<String> wordList) {        if(beginWord == null || endWord == null || wordList == null || beginWord.equals(endWord))            return 0;                int dist = 0;        currentLevel.add(beginWord);        while(!currentLevel.isEmpty()){            dist++;            while(!currentLevel.isEmpty()){                String curWord = currentLevel.remove();                if(curWord.equals(endWord))                    return dist;                                    for(int i = 0; i < curWord.length(); i++){                    char[] wordArray = curWord.toCharArray();                    for(char j = 'a'; j <= 'z'; j++){                        wordArray[i] = j;                        String wordString = new String(wordArray);                        if(wordList.contains(wordString)){                            nextLevel.add(wordString);                            wordList.remove(wordString);                        }                    }                }            }            Queue<String> tmp = nextLevel;            nextLevel = currentLevel;            currentLevel = tmp;        }        return 0;    }        private Queue<String> currentLevel = new ArrayDeque<>();    private Queue<String> nextLevel = new ArrayDeque<>();}


0 0