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. linux-文件系统和目录

    linux目录说明 /:系统根目录 /usr:用户的程序 /home:默认创建用户在此目录下创建用户主目录 /etc:存放系统配置文件.服务脚本,一些程序配置文件 /bin:常用命令 /sbin:常用 ...

  2. E - Apple Tree POJ - 2486

    E - Apple Tree POJ - 2486 Wshxzt is a lovely girl. She likes apple very much. One day HX takes her t ...

  3. Pmw大控件(二)

    Pmw大控件英文名Pmw Python megawidgets 官方参考文档:Pmw 1.3 Python megawidgets 一,如何使用Pmw大控件 下面以创建一个计数器(Counter)为例 ...

  4. git push报错! [rejected] master -> master (non-fast-forward) error: failed to push some refs to 'https://gitee.com/XXX.git

    git pull origin master --allow-unrelated-histories  //把远程仓库和本地同步,消除差异 git add . git commit -m"X ...

  5. nginx_tcp_proxy代理酸酸乳

    一.安装低版本的nginx(高版本不支持tcp代理模块:nginx_tcp_proxy_module)Nginx默认只支持http反向代理,要支持tcp反向代理,需在编译时增加tcp代理模块[ngin ...

  6. JS用例

    showBtn :class="{getInput:showBtn}"v-if="showBtn" showBtn: true, this.showBtn = ...

  7. 股票数据的原始数据形态&数据驱动来设计金融股票业务场景

    1. 数据源 其实金融数据没大家想象的那麽复杂,只需要最原始状态的数据,保存到本地即可以. 那麽,怎样才是股票数据的原始状态呢.那就看看1920's年代的道氏理论,他是怎样计算道琼斯指数,那麽他采用的 ...

  8. mysql查看整库个表详情

    information_schema.tables字段说明 字段 含义 Table_catalog 数据表登记目录 Table_schema 数据表所属的数据库名 Table_name 表名称 Tab ...

  9. 用IMX6开发板创建Android模拟器

    基于迅为IMX6开发板 在 AndroidStudio 中,单击“Tools”->“Android”->“AVD Manager”选项.弹出 如下对话框,点击红色方框中的按钮. 弹出如下所 ...

  10. JS变量、作用域及内存

    1.动态属性var box = new Object();box.name = 'lee';alert(box.name); var box = 'lee';box.age = '28';alert( ...