Merge pull request #1178 from ericL1u/master

127题 增加python解法
This commit is contained in:
程序员Carl
2022-04-12 10:06:35 +08:00
committed by GitHub

View File

@ -134,7 +134,29 @@ public int ladderLength(String beginWord, String endWord, List<String> wordList)
```
## Python
```
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
wordSet = set(wordList)
if len(wordSet)== 0 or endWord not in wordSet:
return 0
mapping = {beginWord:1}
queue = deque([beginWord])
while queue:
word = queue.popleft()
path = mapping[word]
for i in range(len(word)):
word_list = list(word)
for j in range(26):
word_list[i] = chr(ord('a')+j)
newWord = "".join(word_list)
if newWord == endWord:
return path+1
if newWord in wordSet and newWord not in mapping:
mapping[newWord] = path+1
queue.append(newWord)
return 0
```
## Go
## JavaScript