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. PHP的一个小tips (关于=和==或者===的使用)

    由于我在项目中,很多场景判断等式成立的时候 都习惯把值放在==前面(例如 1 == $nStatus), 今天有个同事揪着我问为啥总这样写,回答之后今天也稍作记录下吧. 如果正常些 $nStatus ...

  2. 移动端— position: fixed;固定定位解决方案

    这里有个关键的东西叫做viewport,你经常在页面的头部里可以见到它: <meta name="viewport" content="width=device-w ...

  3. CentOS6.x/6.5/6.4/6.3/6.2/7.x 64位安装php5.2(使用YUM自动安装)

    默认情况下,CentOS6 64 bit 已经早已不支持php5.2.x ,但是某些php程序还需要zend optimizer支持,怎么办呢?目前大部分的yum repos 都已经不支持直接安装ph ...

  4. chenzl

    大噶好!我是计算机6班的陈志良.我是一名代码小白.大一才刚接触代码,我发现我对编程兴趣挺大.特别是每周的代码作业,特别具有挑战性,每当我AC一道,我内心都会有自豪感和兴奋感,尽管过程有挫折,但我仍然坚 ...

  5. windows 安装svn 要点(非安装步骤)

      http://www.visualsvn.com/files/VisualSVN-Server-2.5.6.msi 下载服务端 windows2008搭建svn 1.360软件管家下载 Visua ...

  6. php 文件锁解决并发问题

    阻塞(等待)模式: <?php $fp = fopen("lock.txt", "r"); if(flock($fp,LOCK_EX)) { //.. d ...

  7. Java机器学习软件介绍

    Java机器学习软件介绍 编写程序是最好的学习机器学习的方法.你可以从头开始编写算法,但是如果你要取得更多的进展,建议你采用现有的开源库.在这篇文章中你会发现有关Java中机器学习的主要平台和开放源码 ...

  8. java复制对象,复制对象属性,只可复制两个对象想同的属性名。也可自定义只复制需要的属性。

    注意:使用时copy()方法只会复制相同的属性.常用的copy()方法.以下为封装的工具和使用方式. 1.封装类 import java.util.Map; import java.util.Weak ...

  9. gcc -E xx.c

    C语言代码在交给编译器之前,会先由预处理器进行一些文本替换方面的操作,例如宏展开.文件包含.删除部分代码等. 在正常的情况下,GCC 不会保留预处理阶段的输出文件,也即.i文件.然而,可以利用-E选项 ...

  10. linux中ftp中文名乱码问题

    问题触发环境 1. java中使用org.apache.commons.net.ftp.FTPClient包 2. 通过chrome浏览器的file标签上传文件 3. 在windows上部署的File ...