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:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not the same.

Example 1:

Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"] Output: 5 Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Example 2:

Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"] Output: 0 Explanation: The endWord "cog" is not in wordList, therefore no possible transformation. Solution 1:
Time: O(N^2) lead to TLE
Space: O(N)
 class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if beginWord == endWord or endWord not in wordList:
return 0
step = 1
ladder_dict = self.build_dict(beginWord, wordList)
from collections import deque
queue = deque([beginWord])
visited = {beginWord}
while queue:
size = len(queue)
for i in range(size):
cur_word = queue.popleft()
if cur_word == endWord:
return step
word_lst = ladder_dict.get(cur_word)
for word in word_lst:
if word not in visited:
queue.append(word)
visited.add(word)
step += 1
return 0 def build_dict(self, beginWord, wordList):
my_dict = {}
for w_i in wordList:
my_dict[w_i] = []
for w_j in wordList:
if self.diff(w_i, w_j) == 1:
my_dict[w_i].append(w_j)
if beginWord not in my_dict:
my_dict[beginWord] = []
for w_j in wordList:
if self.diff(beginWord, w_j) == 1:
my_dict[beginWord].append(w_j)
return my_dict def diff(self, s, t):
count = 0
for i in range(len(s)):
if s[i] != t[i]:
count += 1
return count

Solution 2:

Time: O(N * 26^|wordLen|)

Space: O(N)

 class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
if endWord not in wordList:
return 0
import string
from collections import deque
alpha = string.ascii_lowercase
queue = deque([beginWord])
visited = {beginWord}
word_list = set(wordList)
step = 1 while queue:
size = len(queue)
for i in range(size):
cur_word = queue.popleft()
if cur_word == endWord:
return step for i in range(len(cur_word)):
for char in alpha:
new_word = cur_word[:i] + char + cur_word[i+1: ]
if new_word in word_list and new_word not in visited:
queue.append(new_word)
visited.add(new_word)
step += 1
return 0
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
int res = 0, len = 1;
Set<String> dict = new HashSet<>(wordList);
Queue<String> queue = new LinkedList<>();
Set<String> visited = new HashSet<>();
queue.offer(beginWord);
visited.add(beginWord);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String cur = queue.poll();
for(String next : getNextWord(cur, dict)) {
if (visited.contains(next)) {
continue;
}
if (next.equals(endWord)) {
return len + 1;
}
queue.offer(next);
visited.add(next);
}
}
len += 1;
}
return 0;
} private List<String> getNextWord(String cur, Set<String> dict) {
List<String> list = new ArrayList<>();
for (int i = 0; i < cur.length(); i++) {
char[] charArr = cur.toCharArray();
for (char j = 'a'; j <= 'z'; j++) {
if (j == charArr[i]) {
continue;
}
charArr[i] = j;
String newString = new String(charArr);
if (dict.contains(newString)) {
list.add(newString);
}
}
}
return list;
}
}
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Queue<String> queue = new LinkedList<>();
Set<String> set = new HashSet<String>(wordList);
if (!set.contains(endWord)) {
return 0;
}
int res = 0;
set.add(endWord);
queue.offer(beginWord);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String cur = queue.poll();
if (cur.equals(endWord)) {
return res + 1;
} for (int k = 0; k < cur.length(); k++) {
// need to initialize inside of string loop
char[] charArr = cur.toCharArray();
for (int j = 0; j < 26; j++) {
char tmpChar = (char)('a' + j);
if (tmpChar == charArr[k]) {
continue;
}
charArr[k] = tmpChar;
String tmpStr = new String(charArr);
if (set.contains(tmpStr)) {
set.remove(tmpStr);
queue.offer(tmpStr);
}
}
} }
res += 1;
}
return 0;
}
}

[LC] 127. Word Ladder的更多相关文章

  1. 127. Word Ladder(M)

    127. Word LadderGiven two words (beginWord and endWord), and a dictionary's word list, find the leng ...

  2. leetcode 127. Word Ladder、126. Word Ladder II

    127. Word Ladder 这道题使用bfs来解决,每次将满足要求的变换单词加入队列中. wordSet用来记录当前词典中的单词,做一个单词变换生成一个新单词,都需要判断这个单词是否在词典中,不 ...

  3. Leetcode#127 Word Ladder

    原题地址 BFS Word Ladder II的简化版(参见这篇文章) 由于只需要计算步数,所以简单许多. 代码: int ladderLength(string start, string end, ...

  4. 【LeetCode】127. Word Ladder

    Word Ladder Given two words (start and end), and a dictionary, find the length of shortest transform ...

  5. [LeetCode] 127. Word Ladder 单词阶梯

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...

  6. LeetCode 127. Word Ladder 单词接龙(C++/Java)

    题目: Given two words (beginWord and endWord), and a dictionary's word list, find the length of shorte ...

  7. leetcode 127. Word Ladder ----- java

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...

  8. 127 Word Ladder

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...

  9. leetcode@ [127] Word Ladder (BFS / Graph)

    https://leetcode.com/problems/word-ladder/ Given two words (beginWord and endWord), and a dictionary ...

随机推荐

  1. Aras Innovator Method集成Visual Studio

    首先下载集成安装包: https://github.com/RazorleafLabs/Aras-Integration-to-Visual-Studio 解压文件包,找到Aras-Integrati ...

  2. da道至简读后感

    大道至简,衍化至繁. 往往特别深奥的事却是从特别简洁的发展而成的,就像麦克斯韦仅仅凭一个方程组就统一了电磁学一样,物理学中的算式往往非常简练.开普勒计算天体运行的时候是遵循老师认同的地心说计算的,结果 ...

  3. VUE 引用公共样式

    首先创建公共样式文件 在main.js中引用样式 浏览器效果图

  4. 光纤卡网卡的区别以及HBA的常规定义-----引自百度百科

    在讨论这个问题的时候,需要先说清楚一个问题:我们知道,在早期的SAN存储系统中,服务器与交换机的数据传输是通过光纤进行的,因为服务器是把SCSI指令传输到存储设备上,不能走普通LAN网的IP协议,所以 ...

  5. 详细的git入门级别,从安装到实战

    拥有自己码云开源网站,想要上传项目到码云怎么操作?公司新技术提升由Svn转为Git,慌不慌?想要从Github开源网站下载开源项目,难道还依赖直接下载项目然后解压导入项目工程?下面可以通过及其简易且好 ...

  6. MQTT的编译和安装(mosquitto)

    1.基于IBM开发的开元框架实现mosquitto  下载地址:http://mosquitto.org/files/source/ 编译安装:(参考链接:https://www.cnblogs.co ...

  7. -mtime

    大家在使用find命令中的mtime参数时候,会看到官方的解释如下:  -mtime n               File's data was last modified n*24 hours ...

  8. Linux文件目录常用命令

    查看目录内容 ls 切换目录 cd 创建和删除操作 touch rm mkdir 拷贝和移动文件 cp mv 查看文件内容 cat more grep 其他 echo 重定向 > 和 >& ...

  9. Spring(一)——IOC和DI的简单理解

    Spring是一个IOC(DI)和AOP容器框架,并且是开源的. 1.IOC和DI 比较官方的说法: •IOC(Inversion of Control):其思想是反转资源获取的方向. 传统的资源查找 ...

  10. 1 PHP 5.3中的新特性

    1 PHP 5.3中的新特性 1.1 支持命名空间 (Namespace) 毫无疑问,命名空间是PHP5.3所带来的最重要的新特性. 在PHP5.3中,则只需要指定不同的命名空间即可,命名空间的分隔符 ...