题目:
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.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
题意:
给定两个单词(start和end)和一个字典,找出从start到end的最短变换序列的长度,这样:
一次只能换一个字母
每个中间词都必须存在于字典中
例如,
start ="hit"
end ="cog"
dict =["hot","dot","dog","lot","log"]
一个最短的变换是“hit”—>“hot”—>“dot”—>“dog”—>“cog”,
返回其length5。
注意:
如果没有这样的转换序列,返回0。
所有的单词都有相同的长度。
所有单词只包含小写字母。
思路:
这题应该用BFS来解决。首先将start加入队列,然后取出队首字符串,对队首字符串置换一个字母,置换之后与end字符串进行比较,如果相同就返回result+1,不同就查询是否存在于dict中,如果有将其入队,同时在dict中删除(防止重复比较)。重复此流程直到队列为空。
代码:
public int ladderLength(String start, String end, HashSet<String> dict) {
if(start ==null || end == null || dict == null) {
return 0;
}
Queue<String>queue = new LinkedList<String>();
int result = 1;
//入队
queue.offer(start);
while(!queue.isEmpty()) {
for(int k = queue.size(); k>0;k--) {
//取队首值
String str = queue.peek();
//出队
queue.poll();
for(int i=0;i<str.length();i++) {
char[] chs = str.toCharArray();
//遍历字符串,置换字母
for(char j ='a';j<'z';j++) {
chs[i] = j;
String tmp = new String(chs);
//如果和end相等,返回结果
if(tmp.equals(end)) {
return result+1;
}
//如果存在于字典中,入队 同时在字典中删除此字符串,防止重复比较
if(dict.contains(tmp)) {
queue.offer(tmp);
dict.remove(tmp);
}
}
}
}
result++;
}
return 0;
}