Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
1, Only one letter can be changed at a time
2, Each intermediate word must exist in the dictionary
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.
NOTE:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
分析:
单词变形,想到图;
BFS保证最短路径;
因为这里不需要输出路径,因此我们不需要保存前驱节点信息,需要保存的只是单词和距离,可以添加一个node数据结构,也可以用两个队列,来保持word和距离的对应关系。
因为访问一个节点之后就不会再访问,则可以采取从字典里删除的方式来保证不会重复访问,因此,也不需要hash了。
说到底,这是一个图的BFS问题。
public class Solution {
public int ladderLength(String start, String end, HashSet<String> dict) {
if(dict.isEmpty())
return 0;
LinkedList<String> wordQueue = new LinkedList<String>();
LinkedList<Integer> distQueue = new LinkedList<Integer>();
wordQueue.add(start);
distQueue.add(1);
while(!wordQueue.isEmpty()){
String currWord = wordQueue.pop();
Integer currDist = distQueue.pop();
if(currWord.equals(end))
return currDist;
for(int i = 0; i<currWord.length(); i++){
char[] charArr = currWord.toCharArray();
for(char ch='a'; ch<='z'; ch++){
charArr[i] = ch;
String newWord = new String(charArr);
if(dict.contains(newWord)){
wordQueue.add(newWord);
distQueue.add(currDist+1);
dict.remove(newWord);
}
}
}
}
return 0;
}
}