1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
word-ladder.py 2.10 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 5年前 . Update word-ladder.py
# Time: O(b^(d/2)), b is the branch factor of bfs, d is the result depth
# Space: O(w * l), w is the number of words, l is the max length of words
from string import ascii_lowercase
# two-end bfs
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
words = set(wordList)
if endWord not in words:
return 0
left, right = {beginWord}, {endWord}
ladder = 2
while left:
words -= left
new_left = set()
for word in left:
for new_word in (word[:i]+c+word[i+1:] for i in xrange(len(beginWord)) for c in ascii_lowercase):
if new_word not in words:
continue
if new_word in right:
return ladder
new_left.add(new_word)
left = new_left
ladder += 1
if len(left) > len(right):
left, right = right, left
return 0
# Time: O(b^d), b is the branch factor of bfs, d is the result depth
# Space: O(w * l), w is the number of words, l is the max length of words
class Solution2(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
lookup = set(wordList)
if endWord not in lookup:
return 0
ladder = 2
q = [beginWord]
while q:
new_q = []
for word in q:
for i in xrange(len(word)):
for j in ascii_lowercase:
new_word = word[:i] + j + word[i+1:]
if new_word == endWord:
return ladder
if new_word in lookup:
lookup.remove(new_word)
new_q.append(new_word)
q = new_q
ladder += 1
return 0
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助