jinhuang1102

127. Word Ladder

Jan 26th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.02 KB | None | 0 0
  1. """
  2. Word Ladder
  3. 这道题自己卡了很久,主要是没想明白具体要怎么操作BFS,知道看了别人的代码以后,才形成了自己的思路。这道题要用到BFS,还是按照自己熟悉的那个套路来写。
  4. 这道题的思路是:
  5. 1)首先,要想明白在一个word中如何替换每一个letter,如果替换letter后的word出现在wordList中,就把那个word加到BFS的queue中。
  6. 1-1)替换letter的方法:
  7.                     for i in range(0, len(word)):
  8.                         for j in range(97,123): #这一步其实是在遍历26个英文字母的ASCII,然后用chr()把 ASCII 转成字母。
  9.                             temp = word[:i] + chr(j) + word[i+1:] # 这个temp就是遍历每一个char的结果了。
  10. 2)BFS: 既然是BFS那么就要用到deque,首先把 beginWord 加到queue中,然后,用1-1的方法在wordList中寻找word,然后加到deque中。用len(q)确定每一层中含有的word个数,跑完一层word之后把res + 1。在这个过程中如果从deque中pop出来的word == endWrod了那么久返回res + 1。如果跑完所有的word还没有找到的话,最后返回 0
  11. """
  12. class Solution(object):
  13.     def ladderLength(self, beginWord, endWord, wordList):
  14.         """
  15.        :type beginWord: str
  16.        :type endWord: str
  17.        :type wordList: List[str]
  18.        :rtype: int
  19.        """
  20.         st = set(wordList)
  21.        
  22.         q = collections.deque()
  23.         q.append(beginWord)
  24.        
  25.         res = 0
  26.         while q:
  27.             num = len(q)
  28.             for _ in range(num):
  29.                 word = q.popleft()
  30.                 if word == endWord:
  31.                     return res + 1
  32.                 else:
  33.                     for i in range(0, len(word)):
  34.                         for j in range(97, 123):
  35.                             temp = word[:i] + chr(j) + word[i+1:]
  36.                             if temp in st and temp != word:
  37.                                 q.append(temp)
  38.                                 st.remove(temp)
  39.             res += 1
  40.        
  41.         return 0
Add Comment
Please, Sign In to add comment