[LC] 127. Word Ladder
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 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的更多相关文章
- 127. Word Ladder(M)
127. Word LadderGiven two words (beginWord and endWord), and a dictionary's word list, find the leng ...
- leetcode 127. Word Ladder、126. Word Ladder II
127. Word Ladder 这道题使用bfs来解决,每次将满足要求的变换单词加入队列中. wordSet用来记录当前词典中的单词,做一个单词变换生成一个新单词,都需要判断这个单词是否在词典中,不 ...
- Leetcode#127 Word Ladder
原题地址 BFS Word Ladder II的简化版(参见这篇文章) 由于只需要计算步数,所以简单许多. 代码: int ladderLength(string start, string end, ...
- 【LeetCode】127. Word Ladder
Word Ladder Given two words (start and end), and a dictionary, find the length of shortest transform ...
- [LeetCode] 127. Word Ladder 单词阶梯
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...
- LeetCode 127. Word Ladder 单词接龙(C++/Java)
题目: Given two words (beginWord and endWord), and a dictionary's word list, find the length of shorte ...
- leetcode 127. Word Ladder ----- java
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...
- 127 Word Ladder
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...
- leetcode@ [127] Word Ladder (BFS / Graph)
https://leetcode.com/problems/word-ladder/ Given two words (beginWord and endWord), and a dictionary ...
随机推荐
- WOJ 1542 Countries 并查集转化新点+最短路
http://acm.whu.edu.cn/land/problem/detail?problem_id=1542 今天做武大的网赛题,哎,还是不够努力啊,只搞出三个 这个题目一看就是个最短路,但是题 ...
- linux下创建swap分区
两种不同的方式创建swap分区 第一种方法: fdisk /dev/sda n (新建一个分区为/dev/sda6) t (修改分区的id) 82 (swap的id为82) w (重写分区表) par ...
- [ZJCTF 2019]NiZhuanSiWei
0x00知识点 1:data伪协议写入文件 2:php:// php://filter用于读取源码 php://input用于执行php代码 3反序列化 0x01解题 打开题目,给了我们源码 < ...
- 面试易错题 Java
1. int[] arr = new int[10]; System.out.println(arr);//地址值? char[] arr1 = new char[10]; System.out.pr ...
- TF利用分布式队列控制线程
假设分布式任务包含n个ps节点, m个worker节点. m, n>0. 希望所有worker的任务结束后,所有节点才终止. 方法: 借助队列tf.FIFOQueue实现. 原理: tf.FIF ...
- token获取在controller层中
集合判断是否为空 注意:token获取在controller层中,token中存的所有数据都要在controller中获取 在自己的接口里调用别的接口需要判断一下返回值是否为空
- Django专题之ORM操作2
Django ORM操作 目录 一般操作 看专业的官网文档,做专业的程序员! 回到顶部 必知必会13条 <1> all(): 查询所有结果 <2> get(**kwargs ...
- Python常用模块小结
目录 Python常用模块小结 一.Python常用模块小结 1.1 time模块 1.2 datetime模块 1.3 random模块 1.4 os模块 1.5 sys模块 1.6 json模块 ...
- Matlab高级教程_第一篇:Matlab基础知识提炼_05
第九节:矩阵的操作 第十节:数组与矩阵 linspace函数
- 10)global预定义变量
代码展示: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w ...