107人阅读 评论(0)

Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord 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.

public class Solution {

public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
Set<String> beginSet = new HashSet<String>(), endSet = new HashSet<String>();

int len = 1;
int strLen = beginWord.length();
HashSet<String> visited = new HashSet<String>();

while (!beginSet.isEmpty() && !endSet.isEmpty()) {
if (beginSet.size() > endSet.size()) {
Set<String> set = beginSet;
beginSet = endSet;
endSet = set;
}

Set<String> temp = new HashSet<String>();
for (String word : beginSet) {
char[] chs = word.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)) {
}
chs[i] = old;
}
}
}

beginSet = temp;
len++;
}

return 0;
}
}

47ms,beats 89.34%,众数97ms,2.42%
Cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：64680次
• 积分：3289
• 等级：
• 排名：第10725名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：8条
文章分类
阅读排行
最新评论