Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence frombeginWord to endWord, such that:
- Only one letter can be changed at a time
- 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.
解法一: 建一个hashset存储已经可以到达的单词,从beginWord开始,遍历集合中的元素,每个元素中的每一位都挨个用a-z替换来检查是否存在现有的wordlist中,如果存在则放入reached集合中,每遍历一次reached中的元素distance +1,直到reached集合中已经存在endWord 返回distance 即是变化的次数
public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
Set<String> reached = new HashSet<>();
reached.add(beginWord);
wordList.add(endWord);
int distance = 1;
while(!reached.contains(endWord)) {
Set<String> toAdd = new HashSet<>();
for(String each : reached) {
for (int i = 0; i < each.length(); i++) {
char[] chars = each.toCharArray();
for (char ch = 'a'; ch <= 'z'; ch++) {
chars[i] = ch;
String word = new String(chars);
if(wordList.contains(word)) {
toAdd.add(word);
wordList.remove(word);
}
}
}
}
distance ++;
if(toAdd.size() == 0) return 0;
reached = toAdd;
}
return distance;
}
法二:
多了一步比较beginSet和endSet大小,哪个小就从哪个入手开始进行遍历比较
public class Solution {
public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
Set<String> beginSet=new HashSet<>();
Set<String> endSet=new HashSet<>();
int len=1;
HashSet<String> visited=new HashSet<>();
beginSet.add(beginWord);
endSet.add(endWord);
while(!beginSet.isEmpty()&&!endSet.isEmpty()){
if (beginSet.size() > endSet.size()) {
Set<String> set = beginSet;
beginSet = endSet;
endSet = set;
}
Set<String> temp=new HashSet<>();
for(String each:beginSet){
char []chs=each.toCharArray();
for(int i=0;i<chs.length;i++){
for(char c='a';c<='z';c++){
char old=chs[i];
chs[i]=c;
String target=String.valueOf(chs);
if(endSet.contains(target)){
return len+1;
}
if(!visited.contains(target)&&wordList.contains(target)){
temp.add(target);
visited.add(target);
}
chs[i]=old;
}
}
}
beginSet=temp;
len++;
}
return 0;
}
}