forked from walkccc/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0127.py
More file actions
32 lines (26 loc) · 996 Bytes
/
0127.py
File metadata and controls
32 lines (26 loc) · 996 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
wordSet = set(wordList)
if endWord not in wordSet:
return 0
ans = 0
wordLen = len(beginWord)
queue1 = set([beginWord])
queue2 = set([endWord])
while queue1 and queue2:
ans += 1
if len(queue1) > len(queue2):
queue1, queue2 = queue2, queue1
queue = set()
for word in queue1:
for i in range(wordLen):
for j in string.ascii_lowercase:
newWord = word[:i] + j + word[i + 1:]
if newWord in queue2:
return ans + 1
if newWord not in wordSet:
continue
wordSet.remove(newWord)
queue.add(newWord)
queue, queue1 = queue1, queue
return 0