[leedcode 126] Word Ladder

Given two words (beginWord and endWord), and a dictionary, 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 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.

public class Solution {
    public int ladderLength(String beginWord, String endWord, Set<String> wordDict) {
        //BFS,利用队列保存在dict中出现的单词,并且记录level和count,从队列中取出每一个字符串,对字符串的每一位进行替换,如果存在于dict就添加         //到队列里,并且从dict删除 超时TLE
        if(beginWord.length()!=endWord.length())return 0;
        LinkedList<String> queue=new LinkedList<String>();
        queue.add(beginWord);
        int level=1;
        int count=1;
        wordDict.remove(beginWord);
        while(!queue.isEmpty()&&wordDict.size()>0){
          while(count>0){
            String word=queue.remove();
            count--;
            StringBuilder temp=new StringBuilder(word);
            for(int i=0;i<word.length();i++){
                for(char j='a';j<='z';j++){
                    if(word.charAt(i)==j)continue;
                    char s=temp.charAt(i);
                    temp=temp.replace(i,i+1,j+"");
                    if(temp.equals(endWord)) return level+1;
                    if(wordDict.contains(temp.toString()))
                     {
                            queue.add(temp.toString());
                            wordDict.remove(temp.toString());
                     }
                    temp.replace(i,i+1,s+"");
                }
            }
          }
         
         count=queue.size();
         level++;
        }
        return 0;
    }
}

 

你可能感兴趣的:(code)