1.题目
给定两个单词(开始和结束)和一个字典,从头到尾查找最短变换序列的长度,以便:
一次只能更改一个字母,每个中间词必须存在于词典中
例如,给定:
start ="hit"
end ="cog"
dict =["hot","dot","dog","lot","log"]
由于最短的一个转换是"hit" -> "hot" -> "dot" -> "dog" -> "cog",所以返回5。
2.分析过程
深度优先遍历的应用,当然也可以是广度优先遍历。
3.代码实现
import java.util.*;
public class Solution {
public int ladderLength(String start, String end, HashSet<String> dict) {
if(start==null || start.length()==0 || end==null || end.length()==0 || start.length()!=end.length())
return 0;
if(isSimlary(start,end)){
return 2;
}else{
if(dict==null || dict.size()==0){
return 0;
}
}
Queue<String> queue=new LinkedList<>();
HashSet<String> set=new HashSet<>();
set.addAll(dict);
queue.offer(start);
int res=1;
while(!queue.isEmpty()){
set.removeAll(queue);
int size=queue.size();
while(size>0){
String str=queue.poll();
for(Iterator<String> it=set.iterator();it.hasNext();){
String temp=it.next();
if(isSimlary(str,temp)){
if(isSimlary(temp,end)){
return res+2;
}else{
queue.offer(temp);
}
}
}
size--;
}
res++;
}
return 0;
}
public boolean isSimlary(String start,String end){
int count=0;
for(int i=0;i<start.length();i++){
if(start.charAt(i)!=end.charAt(i))
count++;
}
if(count==1) return true;
else return false;
}
}
题目来自牛客网leetcode