[leetcode] word-ladder
题目描述:
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
Only one letter can be changed at a time
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 length5.
解题思路:
应利用广度优先遍历(即树的的层序遍历)解决此题。
- 定义两个LinkedList:word存单词,num记录更改的次数
- 先从word这个linkedList中弹出一个单词,若弹出的单词是end单词,则返回num里弹出的次数。否则,从第一个字母开始更换a~z中的任意一个字母,若字典中存在新生成的单词,则将新单词压入word中,相应的次数加一压入num中,并且从字典中删除这个单词。
如:
hit 更换第一个字母时,字典里不包含新生成的所有单词。
同理再更换第二个字母,可以看出字典中包含新单词hot,则将hot压入word中,相应的步数加1,压入num中。
如此替换,直到word里弹出的是end,返回num中弹出的步数。
代码:
import java.util.HashSet;
import java.util.LinkedList;
public class Solution {
public int ladderLength(String start, String end, HashSet<String> dict) {
if(start==null||end==null||start.equals(end)){
return 0;
}
int len=start.length();
LinkedList<String> word=new LinkedList<String>();
LinkedList<Integer> count=new LinkedList<Integer>();
word.add(start);
count.add(1);
while(word.size()!=0){
String curWord=word.pop();
int curCount=count.pop();
if(curWord.equals(end)){
return curCount;
}
for(int i=0;i<len;i++){
char[] curWordChar=curWord.toCharArray();
for(char c='a';c<='z';c++){
curWordChar[i]=c;
String newWord=new String(curWordChar);
if(dict.contains(newWord)){
word.add(newWord);
count.add(curCount+1);
dict.remove(newWord);
}
}
}
}
return 0;
}
}
注:
在这里解释一下树的层序遍历
规则是若数为空,则空操作返回,否则从树的第一层,也就是根节点开始访问,从上而下逐层遍历,在同一层中,按从左到右的顺序对节点逐个访问。