127. Word Ladder

来源:互联网 发布:内涵段子软件下载 编辑:程序博客网 时间:2024/05/29 07:10

题目:

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:

Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,

Given:
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,”dot”,”dog”,”lot”,”log”,”cog”]
As one shortest transformation is “hit” -> “hot” -> “dot” -> “dog” -> “cog”,
return its length 5.
在一次只能改变一个字母的情况下,找出beginWord 需要几次可以变换为endWord。

  • 思路:假设两个只相差一个字母的单词为“邻居”,利用BFS算法的思想,先找出与beginWord“邻居”并存放在Set集合里。再找出Set集合里每个单词的邻居并存放在Set集合里,以此类推,当找到endWord后结束。
public static int ladderLength(String beginWord, String endWord, List<String> wordList) {        int diatance=1;        Set<String> current= new HashSet<String> ();        Set<String> v= new HashSet<String> (wordList);        current.add(beginWord);        if(!v.contains(endWord))            return 0;        while(current.size()>0 && !current.contains(endWord)){            Set<String> tempQueue= new HashSet<String> ();            for(String word:current){                for(int i=0;i<word.length();i++){                    StringBuilder builder=new StringBuilder(word);                    String tempWord="";                    char tempChar=word.charAt(i);                    for(char ch='a';ch<='z';ch++){                        if(tempChar==ch)                            continue;                        else{                            builder.setCharAt(i,ch);                            tempWord=builder.toString();                        }                        if (tempWord.equals(endWord) )                            return diatance+1;                        if (v.contains(tempWord)){                            tempQueue.add(tempWord);                            v.remove(tempWord);                        }                    }                }            }            current=tempQueue;        }        return 0;    }
原创粉丝点击