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. CSS(3)之 less 和rem

    less 预编译脚本语言. LESS 语法 less语法2 LESS中文 rem rem的适配原理 rem 是相对于页面根源素html的字体大小的一个尺寸单位 页面内容可以使用rem为单位,那么htm ...

  2. CocoaPods为多个target添加依赖库/Podfile的配置

    Podfile的相关配置,请看官方文档http://guides.cocoapods.org/syntax/podfile.html 1)多个target公用相同库,还可以添加额外的不同第三方库 编辑 ...

  3. 更新anaconda包

    升级安装python环境后, 把老的包重新安装回去. ls -l /opt/anaconda3/lib/python3.7/site-packages/ | grep "\-info&quo ...

  4. 寒假day08

    今天爬了部分与人才动态相关的数据,还刷了剑指offer的部分算法题

  5. 1.2 NumPy数组基础

    目录 第一章 numpy入门 1.2 numpy数组基础 1.2.1 数组的属性 1.2.2 数组的索引:获取单个元素 1.2.3 数组切片:获取子数组 1.2.4 数组的变形 1.2.5 数组的拼接 ...

  6. cmd执行jmeter命令生成报告的问题。

    现有几个jmeter脚本,准备以命令行的方式执行jmeter脚本,并生成报告. 一.使用python语言处理 1.目录结构 2.说明 jmx目录下是jmeter脚本 result目录下是生成的报告及文 ...

  7. 十、GUI编程

    GUI图形用户界面编程       GUI编程类似“搭积木”,将一个个组件放到窗口中,并通过增加“事件处理”,完成一个个程序.例如:记事本.word.画图工具等. tkinter模块 tkinter是 ...

  8. electron-builder打包跳过publish

    默认情况下执行 npm run release使用build命令打包时自动将打包好的安装程序发布到仓库,有时候不需要每次打包都上传到仓库,这时我们只需要在build命令后面加上参数-p never 即 ...

  9. Maven--Maven 入门

    1.POM <?xml version="1.0" encoding="utf-8" ?> <project xmlns="http ...

  10. MySQL--INSERT INTO ... ON DUPLICATE KEY UPDATE ...

    转自:https://my.oschina.net/iceman/blog/53735 如果在INSERT语句末尾指定了ON DUPLICATE KEY UPDATE,并且插入行后会导致在一个UNIQ ...