Word Ladder
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
#wordList.append(endWord)
q = []
q.append((beginWord,1))
while q:
(curr,lenth) = q.pop(0)
if curr == endWord:
return lenth
for i in range(len(curr)):
part1 = curr[:i]
part2 = curr[i+1:]
for j in 'abcdefghijklmnopqrstuvwxyz':
if curr[i] != j:
nextword = part1 + j + part2
if nextword in wordList:
q.append((nextword,lenth+1))
wordList.remove(nextword)
return 0
但這一題其實是在卡時間,卡的比較嚴格,所以需要把wordlist換成python字典格式,這樣在搜尋的時候就從o(n)變成o(1)了
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: Set[str]
:rtype: int
"""
dic = {}
for w in wordList:
if w not in dic:
dic[w] = 1
q = [(beginWord,1)]
while q:
e,lens = q.pop(0)
if e == endWord: return lens
for i in range(len(e)):
left = e[:i]
right = e[i + 1:]
for c in 'abcdefghigklmnopqrstuvwxyz':
if e[i] != c:
nextWord = left + c + right
if nextWord in dic:
q.append((nextWord,lens + 1))
del dic[nextWord]
return 0
相關文章
- *** 126. Word Ladder II
- 126-Word Ladder II
- 6570USST Ladder Based State Design Exercise
- pdf轉word格式PDF to word for MacMac
- Hello Word!
- hello word
- word 2021:Word 2021 LTSC for Mac 中文版Mac
- word-break 和 word-wrap 的區別
- word-wrap同word-break的區別
- pdf 轉 word
- word小程式
- Leetcode Word SearchLeetCode
- Java操作WordJava
- Character Specifications for A Word
- linux - word frequencyLinux
- Python操作WordPython
- docxtpl - word模板
- Word 工作技巧
- [PY] Word 處理, 技術選型, Word 轉 PDF
- 區分 word-wrap/word-break/white-space
- 壓縮Word,一鍵實現Word文件壓縮
- pdf轉word工具推薦 PDF to word 最新啟用版
- word公式怎麼計算 word公式計算的方法公式
- python word 應用,設定 word 文件的內容格式Python
- 徹底搞懂word-break、word-wrap、white-space
- Word2Vec
- word常規操作
- Word 2021 LTSC for MacMac
- WPS使用技巧|word
- Microsoft Word 2021 for MacROSMac
- CSS word-breakCSS
- 139. Word Break
- 【PY】Word 轉 PDF
- Solidity教程 hello wordSolid
- java生成word文件Java
- 自定義 Word 模板
- Python加密word文件Python加密
- pdf轉word工具:PDF to word for Mac v8.5.6啟用版Mac