127. Word Ladder
Medium
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:
- Only one letter can be changed at a time.
- Each transformed word must exist in the word list.
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.
笔记:
利用BFS去解决。通过替换一个单词中的字母去判断该单词是否在wordList中。
当只是查询某个值是否在一个变量里面的时候,set/dict 比List更高效,set/dict的查询是O(1), list是O(n).
按索引查询,list的效率是O(1),set的是O(n)。
list在头部插入或者删除的时候,效率是O(n)
deque双端队列,在两段插入或者删除的效率都是O(1), deque不要使用切片(会抛出异常)和索引(效率为O(n))。deque的双端索引效率是O(1), 但是任意位置访问的话,效率是O(n),所以当需要索引访问的时候,使用list
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
word_set = set(wordList)
if endWord not in word_set:
return 0
que = collections.deque()
que.append((beginWord,1))
while que:
word, step = que.popleft()
for i in (range(len(word))):
for s in 'abcdefghijklmnopqrstuvwxyz':
new_word = word[:i] + s + word[i + 1:]
if new_word in word_set and new_word != word:
if new_word == endWord:
return step + 1
que.append((new_word, step + 1))
word_set.remove(new_word)
return 0
参考:https://blog.csdn.net/fuxuemingzhu/article/details/82903681