A classic BFS problem, that is, we use a Queue to store temporary solution and record the size of the current Queue.
For each node in this BFS tree, we try k times of transformation, k is the length of the word.
We record every word which already has been seen in case of a loop. Thus we need a HashSet.
public class Solution {
// use BFS to solve
// in every level of BFS searching,
// we find the word that replaced by one char and also in the dict without have seen before
// data structure: seen(HashSet), cur(Queue)
// assume that the wordList is not null, case insensitive, no duplicate, every word is non-empty
public int ladderLength(String beginWord, String endWord, List
// Write your solution here
HashSet
Queue
seen.add(beginWord);
cur.offer(beginWord);
int cnt = 1;
while(cur.size()>0){
cnt++;
int size = cur.size();
for(int i=0; i
for(String s: changed){
if(String.valueOf(s)==String.valueOf(endWord)){
return cnt;
}else{
cur.offer(s);
seen.add(s);
}
}
}
}
}
return 0;
}
private List
List
for(String s: wordList){
int flag = 0;
for(int i=0; i<from.length(); i++){
if(i!=ignore && from.charAt(i)!=s.charAt(i)){
flag=1;
}
}
if(flag==0 && !seen.contains(s)){
res.add(s);
}
}
return res;
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章